Linq与自定义基础集合 [英] Linq with custom base collection

查看:74
本文介绍了Linq与自定义基础集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用自定义集合对象时,我经常发现linq有问题. 他们通常被定义为

I often find linq being problematic when working with custom collection object. They are often defened as

基础收藏

abstract class BaseCollection<T> : List<T> { ... }

集合定义为

class PruductCollection : BaseCollection<Product> { ... }

是否有比linq expession更好的方法添加此集合的方法? addrange还是concat?

Is there a better way to add results from a linq expession to this collection than addrange or concat?

var products = from p in HugeProductCollection
               where p.Vendor = currentVendor
               select p;
PruductCollection objVendorProducts = new PruductCollection();
objVendorProducts.AddRange(products);

如果从linq查询返回的对象是我的自定义集合类型,那就太好了.您似乎需要两次枚举集合才能做到这一点.

It would be nice if the object returned form the linq query was of my custom collection type. As you seem to need to enumerate the collection two times to do this.

编辑: 阅读答案后,我认为最好的解决方案是实现ToProduct()扩展. 不知道c#4.0中的协方差/协方差是否会帮助解决这类问题.

EDIT : After reading the answers i think the best solution is to implementa a ToProduct() extention. Wonder if the covariance/contravariance in c#4.0 will help solve these kinds of problems.

推荐答案

问题是LINQ通过IEnumerable<T>上的扩展方法,知道如何构建数组,列表和字典,但不知道如何构建您的自定义收藏.您可以让您的自定义集合具有采用IEnumerable<T>的构造函数,也可以编写您的代码.前者将允许您直接在构造函数中使用LINQ结果,后者将允许您使用扩展名装饰LINQ语句并获取所需的集合.无论哪种方式,您都需要在构造函数或扩展程序中进行从通用集合到专用集合的某种转换.或者您可以同时做...

The problem is that LINQ, through extension methods on IEnumerable<T>, knows how to build Arrays, Lists, and Dictionaries, it doesn't know how to build your custom collection. You could have your custom collection have a constructor that takes an IEnumerable<T> or you could write you. The former would allow you to use the LINQ result in your constructor directly, the latter would allow you to decorate the LINQ statement with your extension and get back the collection you desire. Either way you'll need to do some sort of conversion from the generic collection to your specialized collection -- either in the constructor or in the extension. Or you could do both...

public static class MyExtensions
{
     public static ProductCollection
                      ToProducts( this IEnumerable<Product> collection )
     {
          return new ProductCollection( collection );
     }
}


public class ProductCollection : BaseCollection<Product>
{
     ...

     public ProductCollection( IEnumerable<Product> collection )
              : base( collection )
     {
     }

     ...
 }


var products = (from p in HugeProductCollection
                where p.Vendor = currentVendor
                select p).ToProducts();

这篇关于Linq与自定义基础集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆