Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<Company> to List<ICompany>

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?

like image 549
Robs Avatar asked Nov 27 '22 12:11

Robs


1 Answers

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>();
}
like image 110
jason Avatar answered Dec 16 '22 02:12

jason