2011-03-23 66 views
3
void Main() 
    { 
     List<SomeContainer> someList = new List<SomeContainer>(); 
     someList.Add(new SomeContainer { a = true, b = true, c = true }); 
     someList.Add(new SomeContainer { a = false, b = true, c = false }); 
     someList.Add(new SomeContainer { a = true, b = true, c = false }); 
     someList.Add(new SomeContainer { a = true, b = false, c = false }); 
     someList.Add(new SomeContainer { a = true, b = false, c = false }); 
     someList.Add(new SomeContainer { a = true, b = true, c = false }); 
     someList.Add(new SomeContainer { a = true, b = true, c = false }); 

     var q1 = from container in someList where container.a == true select container.a; 
     var q2 = from container in someList where container.b == true select container.b; 
     var q3 = from container in someList where container.c == true select container.c; 
     q1.Count().Dump(); 
     q2.Count().Dump(); 
     q3.Count().Dump(); 
    } 

    class SomeContainer 
    { 
     public Boolean a { get; set; } 
     public Boolean b { get; set; } 
     public Boolean c { get; set; } 
    } 

是否有可能通过一个问答生成类似这样的内容:
a | b | c
6 | 5 | 1减少LINQ查询的数量

回答

1
int a = 0, b = 0, c = 0; 
var qAll = (from ct in someList 
      select new{ ac = ct.a ? a++ : 0, 
         bc = ct.b ? b++ : 0, 
         cc = ct.c ? c++ : 0}).ToList(); 

//Now a, b, c variables should have the count of a==true, b==true & c==true in somelist. 
//Console.WriteLine("A= {0}, B={1}, C={2}", a, b, c); 
+1

所以有可能在一个查询中做到这一点!完美解决方案 – 2011-03-24 12:53:10

4

不知道你是否会将此作为一个优化,但是这将遍历列表只有一次:

var result = someList 
     .Select(i => new [] {i.a? 1:0, i.b? 1:0, i.c? 1:0,}) 
     .Aggregate((i, acc) => new [] {i[0]+acc[0], i[1]+acc[1], i[2]+acc[2]}); 

int countA = result[0]; 
int countB = result[1]; 
int countC = result[2]; 
+0

+1这个答案,我会亲自解决的'INT aCount = someList.Count(X => XA) ;'(b,c)虽然为了可读性。 – BrokenGlass 2011-03-23 22:57:37

+0

@BrokenGlass,同意,但这不是关于可读性。无论如何它都可以很好地知道这个想法,因为它可以与纯SQL一起工作,所以它可以优化常规的SQL查询。 – Snowbear 2011-03-23 22:59:20

+0

现在我知道关于Aggregate的一切。 BrokenGlass的解决方案非常简单。感谢您的快速响应。 – 2011-03-24 01:21:06

0

Aggregate扩展方法允许你从可枚举以任意方式组合值。您可以聚合代表计数的三个整数的元组,并提供一个函数,用于根据输入增加元组上的三个计数器。

它怀疑它可能看起来这个例子是人为设计的,它可能比常规的for循环慢。

有时候Aggregate尽管闪耀。我用它来计算矩形列表的边框:var union = rects.Aggregate(Rectangle.Union);

0
someList.Count(container => container.a).Dump(); 
someList.Count(container => container.b).Dump(); 
someList.Count(container => container.c).Dump(); 
//even when looking for false values it looks nice... 
someList.Where(container => container.a == false).Count(container => container.a).Dump();