开发者

How to return a driven collection of [List<>] after filtering by [Where]?

In the following collection:

public class PersonsCollection : List<Person>

How can I return an instance of PersonsCollection after filtering by Where extension?

personCollections.Where(p => p.Name == "Jack").T开发者_如何转开发oList(); 
// will return IEnumerable<Person>, How to return PersonsCollection?

Any idea!


You´d have to create a new instance of PersonsCollection instead, e.g.

return new PersonsCollection(personsCollection.Where(p => p.Name == "Jack"))

assuming you have an appropriate constructor.

Generally it´s a bad idea to extend the built-in collections anyway (rather than using composition) - are you sure you want this design in the first place?


You could to create an Extension Method ToList() for an IEnumerable<Person>...

public static class PersonCollectionExtensions
{
    public static List<Person> ToList(this IEnumerable<Person> self)
    {
         return new PersonCollection(self);
    }
}


Something like this:

var pc = new PersonCollection();
pc.AddRange(personCollections.Where(p => p.Name == "Jack").ToArray());
return pc;


A few possibilities:

  1. Your PersonsCollection has a constructor that accepts an IEnumerable<Person>, so you create a new PersonsCollection based on the query result.

  2. You can create a new extension method ToPersonsCollection() that constructs the PersonsCollection (may be combined with the above.)

  3. You can change your dependencies so that other code doesn't require a PersonsCollection and can instead work with IEnumerable<Person> (this is the option that I'd recommend.)


You need to create the proper constructor in your collection:

public class PersonsCollection : List<Person> {
  public PersonsCollection() { }
  public PersonsCollection(IEnumerable<Person> persons) : base(persons) { }
}

You can then filter it like this:

new PersonsCollection(personCollections.Where(p => p.Name == "Jack"));

From your comment about CollectionBase I guess that you are refactoring old code not using generics. Krzysztof Cwalina made a blog post about how to transition from non-generic collections to generic collections. You may also find his comment on a blog post why List<T> isn't recommended in public API's interesting:

We recommend using Collection<T>, ReadOnlyCollection<T>, or KeyedCollection<TKey,TItem> for outputs and properties and interfaces IEnumerable<T>, ICollection<T>, IList<T> for inputs.

You could simply get rid of PersonsCollection and use something like Collection<Person> instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜