Linq对象集合的结果

bre*_*ton 4 .net c# linq

我有一个问题,我可以解决,但我觉得Linq中应该有一个我只是没有看到的解决方案.

所以我有两个类,一个详细记录类和这些类的集合:

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

public class ItemDetailCollection : List<ItemDetail>
{
}
Run Code Online (Sandbox Code Playgroud)

现在,我可以使用我的存储库层填充这些对象而没有问题,并查询数据以获取我想要的记录子集.

var items = Repository.GetItemCollection();
var reportItemCollection = items.Where(x=>x.Id.HasValue);
Run Code Online (Sandbox Code Playgroud)

这一切都很好,花花公子.然而,这reportItemCollection是一个IEnumberable<ItemDetail>,我真正想要的是一个新的ItemDetailCollection.

当然,我可以创建一个新的集合并添加查询范围,但我觉得有一种方法可以自动将结果集填充为特定的集合类型.我尝试添加以下内容,只收到以下结果NULL:

var reportItemCollection = items.Where(x=>x.Id.HasValue) as ItemDetailCollection;
Run Code Online (Sandbox Code Playgroud)

尝试.Cast<ItemDetailCollection>()也不起作用.最后,我试过了

var reportItemCollection = items.Where(x=>x.Id.HasValue).Select(result => new ItemDetailCollection(){ result });
Run Code Online (Sandbox Code Playgroud)

但这只给了我一个IEnumerable<ItemDetailCollection>.

有什么想法吗?

McG*_*gle 9

唯一的方法是使用构造函数实际构造集合List<T>:

public class ItemDetailCollection : List<ItemDetail>
{
    public ItemDetailCollection(IEnumerable<ItemDetail> items)
        : base(items) { }
}
Run Code Online (Sandbox Code Playgroud)

var reportItemCollection = new ItemDetailCollection(
    items.Where(x=>x.Id.HasValue)
);
Run Code Online (Sandbox Code Playgroud)

由于协方差/逆变规则,你无法将类型强制IEnumerable<T>转换为子类ItemDetailCollection(请参阅此处,例如:http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance- and-contravariance-faq.aspx).