在这种情况下,我有两个不同的LINQ表达式来从两个不同条件的产品计数.我只是好奇是否可以从一个LINQ表达式中检索这两个计数?
class Program
{
static void Main(string[] args)
{
List<Product> Products = new List<Product>()
{
new Product() { ID = 1 },
new Product() { ID = 2 },
new Product() { ID = 3 },
new Product() { ID = 4 },
new Product() { ID = 5 },
new Product() { ID = 6 }
};
int all = Products.Count();
int some = Products.Where(x => x.ID < 2).Count();
}
}
public class Product
{
public int ID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用Aggregate
您可以避免两次迭代您的集合:
var result = Products.Aggregate(new {a=0, s=0},(p,c) =>
{
return new { a = p.a + 1, s = c.ID < 2 ? p.s + 1 : p.s };
});
Run Code Online (Sandbox Code Playgroud)
现在result.a == 6
和result.s == 2
当然,您可以创建一个类来保存您的结果,而不是使用匿名类型,它的工作方式大致相同.例如,如果你必须从一个函数返回它,这可能更容易处理.
所以你可以这样做:
public class CountResult
{
public int All { get; set; }
public int Some { get; set; }
}
public CountResult GetMyCount(IEnumerable<Product> products)
{
return products.Aggregate(new CountResult(), (p,c) =>
{
p.All++;
if (c.ID < 2) // or whatever you condition might be
{
p.Some++;
}
return p;
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
107 次 |
最近记录: |