Linq选择两个不同类型的列
本文关键字:同类型 两个 选择 Linq | 更新日期: 2023-09-27 18:26:19
我有以下Linq查询:
var dis = productsWhole
.SelectMany(p => p.CustomerPricing).ToList();
这允许foreach访问productsWhole.Customer定价列表中的每个项目。
productsWhole ienumerable还包含一个字符串字段ProductCode有没有一种方法可以在不使用select新的匿名类型的情况下将两者组合起来?
按照@test的建议,投影到Tuple
的正确方法是使用SelectMany重载,它支持像这样的附加resultSelector
var dis = productsWhole
.SelectMany(p => p.CustomerPricing, (p, cp) => Tuple.Create(p.ProductCode, cp))
.ToList();
如果你关心的是匿名类型部分(我想你想从一个方法或类似的东西中返回它),要么将其投影到已知类型(如测试建议的Tuple),要么投影到预定义类型(如你自己的结构或类),例如:
internal class ProductProjection
{
internal CustomerPricing CustomerPricing { get; set; }
internal string ProductCode { get; set; }
}
然后执行:
var dis = productsWhole
.SelectMany(p => new ProductProjection { CustomerPricing = p.CustomerPricing, ProductCode = p.ProductCode }).ToList();
dis
将成为List<ProductProjection>