gpt4 book ai didi

c# - 带有自定义基础集合的 Linq

转载 作者:太空狗 更新时间:2023-10-29 20:19:06 25 4
gpt4 key购买 nike

在处理自定义集合对象时,我经常发现 linq 有问题。它们通常被定义为

基础集合

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

集合定义为

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

有没有比将 linq expession 的结果添加到这个集合更好的方法添加范围还是连接?

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

如果从 linq 查询返回的对象是我的自定义集合类型,那就太好了。因为您似乎需要两次枚举集合才能执行此操作。

编辑:阅读答案后,我认为最好的解决方案是实现 ToProduct() 扩展。想知道c#4.0中的协变/逆变是否有助于解决这类问题。

最佳答案

问题是 LINQ,通过 IEnumerable<T> 上的扩展方法,知道如何构建数组、列表和字典,它不知道如何构建自定义集合。你可以让你的自定义集合有一个接受 IEnumerable<T> 的构造函数或者你可以写信给你。前者允许您直接在构造函数中使用 LINQ 结果,后者允许您使用扩展修饰 LINQ 语句并取回您想要的集合。无论哪种方式,您都需要在构造函数或扩展中进行某种从通用集合到专用集合的转换。或者你可以两者都做...

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();

关于c# - 带有自定义基础集合的 Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/371174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com