[英]combining two LINQ expressions into one
在這種情況下,我有兩個不同的LINQ表達式,可以從Products中為兩個不同的條件計數。 我只是好奇是否可以從一個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; }
}
使用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 };
});
現在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;
});
}
您可以使用Tuple<int, int>
來做到這一點:
var result = new Tuple<int, int>(Products.Count, Products.Where(x => x.ID < 2).Count());
並且請注明使用具有O(1)復雜度而不是O(N)的Products.Count
屬性,因此您完全不必擔心此實現的性能。 為了進一步閱讀,您可以查看這篇文章 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.