Linq results where objects are collected

I have a problem that I can work with, but I feel that there should be a solution in Linq that I just don't see.

So, I have two classes: a data record class and a collection of these classes:

public class ItemDetail
{
    public string Name {get;set;}
    public int? Id {get;set;}
}

public class ItemDetailCollection : List<ItemDetail>
{
}

Now I can populate these objects with my repository level without any problems and query the data to get a subset of the required records.

var items = Repository.GetItemCollection();
var reportItemCollection = items.Where(x=>x.Id.HasValue);

It's all beautiful and dandy. However, it reportItemCollectionis IEnumberable<ItemDetail>, and I really want a new one ItemDetailCollection.

Of course, I could create a new collection and add a range of queries, but I feel that there is a way to automatically populate the result set as a specific type of collection. I tried adding the following and getting the results only as NULL:

var reportItemCollection = items.Where(x=>x.Id.HasValue) as ItemDetailCollection;

.Cast<ItemDetailCollection>() . ,

var reportItemCollection = items.Where(x=>x.Id.HasValue).Select(result => new ItemDetailCollection(){ result });

IEnumerable<ItemDetailCollection>.

?

+4
2

- , List<T>:

public class ItemDetailCollection : List<ItemDetail>
{
    public ItemDetailCollection(IEnumerable<ItemDetail> items)
        : base(items) { }
}

var reportItemCollection = new ItemDetailCollection(
    items.Where(x=>x.Id.HasValue)
);

IEnumerable<T> ItemDetailCollection - / (. , : http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx).

+9

, LINQ List<T>: ToItemDetailCollection

static ItemDataCollection ToItemDataCollection(this IEnumerable<ItemDetail> e) {
  return new ItemDataCollection(e);
}

var reportItemCollection = items
  .Where(x=>x.Id.HasValue)
  .ToItemDataCollection();

, List<T>. virtual , , . List<ItemDetail> , .

+4

Source: https://habr.com/ru/post/1525851/


All Articles