Answer the question
In order to leave comments, you need to log in
What should be the search result if there is no data?
Let's take the classical scheme, base and application.
The application has a class for working with the database, there is a search method for a specific field, which should return data in a certain structure
class SomeRecord
{
public string prop1 {get;set;}
public string prop1 {get;set;}
}
public SomeRecord FindMe(string prop)
{
var l = <linq query>
return l.First<SomeRecord>();
}
Answer the question
In order to leave comments, you need to log in
That's right - return a collection of search results. If there are no results, an empty collection will be returned.
If your contract is such that "only one result should be returned", then FindMe should throw an exception, because it failed to fulfill the "return one result" contract (null is not a result).
Null can only be returned if you actually want to use the "return one result or null" contract. But such a design does not lead to anything good and only increases complexity.
return l.FirstOrDefault<SomeRecord>();
and expect a possible null as a result. Either process the response before returning
public SomeRecord FindMe(string prop)
{
var l = <linq query>
SomeRecord result = l.FirstOrDefault<SomeRecord>();
if(result == null) {
result = new SomeRecord();
}
return result;
}
var result = l.SingleOrDefault();
1. Here is another option for further processing: use something like Option from F # (or Nullable in C #)
So that the method contract would be immediately clear
public class SingleResult<T> where T : class {
private readonly T result;
public readonly bool IsSuccess;
private SingleResult(T result, bool isSuccess) {
this.result = result;
IsSuccess = isSuccess;
}
public T Result {
get {
Contract.Requires<InvalidOperationException>(IsSuccess);
return result;
}
}
public static SingleResult<T> Success(T result) {
Contract.Requires<ArgumentNullException>(result != null, "result");
return new SingleResult<T>(result, true);
}
public static SingleResult<T> Nothing = new SingleResult<T>(null, false);
}
public SingleResult<SomeRecord> FindMe(string prop) {
var l = <linqquery >;
var result = l.SingleOrDefault();
if (result == null)
return SingleResult<SomeRecord>.Nothing;
return SingleResult<SomeRecord>.Success(result);
}
public bool TryFindSingle(string prop, out SomeRecord result) {...}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question