I would like to convert List<Company>
to List<ICompany>
ICompany
is an interface which Company
implements.
public List<ICompany> FindAll()
{
List<Company> companies = new List<Company>();
var query = from c in _scope.Extent<Company>()
select c;
companies = query.ToList();
return companies.ToList<ICompany>(); // doesn't work
//and
return companies.ToList(); // doesn't work
}
Any thoughts?
Use Enumerable.Cast
:
return query.Cast<ICompany>().ToList();
A few comments:
List<Company> companies = new List<Company>();
This creates a new list. But you never use it because two lines later you have
companies = query.ToList();
overwriting the list that you created (and in the intermediate line you never refer to companies
). If you want, you can declare and obtain the results in one fell swoop:
List<Company> companies = query.ToList();
Second, all this is unnecessary if you're just trying to return a list of the results. Brevity (to an extent) is a big plus in programming. "Less is more" is the saying as less code means less code to write, less code to test and less code to maintain. Instant productivity increase by writing less code! Here's a short version of your method:
public List<ICompany> FindAll() {
var query = from c in _scope.Extent<Company>()
select c;
return query.Cast<ICompany>().ToList();
}
or even
public List<ICompany> FindAll() {
return _scope.Extent<Company>().Cast<ICompany>().ToList();
}
Third, at a minimum, you should consider returning an IList
instead of List
. It is better to code to interfaces rather than concrete types. This decouples your code from implementation details making the code more amenable to change and easier to test.
Lastly, you should examine if you really need to return a List
. What methods on list are you using? If you merely are using it to enumerate the results (foreach(var item in list)
) then you should instead return an IEnumerable<ICompany>
:
public IEnumerable<ICompany> FindAll() {
return _scope.Extent<Company>().Cast<ICompany>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With