2016-09-20 68 views
-1

我想要做的是取一個對象的IEnumerable有2個字段,並找出有多少個字段只與第一個字段相關聯。如何使用LINQ查詢來做到這一點?

換句話說,該設置是這樣

using System; 
using System.Linq; 
using System.Collections.Generic; 

public class Baz 
{ 
    public string Foo { get; set; } 
    public int Bar { get; set; }  
} 

public class Program 
{ 
    public void Main() 
    { 
     List<Baz> bazzers = new List<Baz>() { 

      new Baz { Foo = "A", Bar = 1 }, 
      new Baz { Foo = "A", Bar = 3 }, 
      new Baz { Foo = "B", Bar = 1 }, 
      new Baz { Foo = "B", Bar = 1 }, 
      new Baz { Foo = "C", Bar = 2 }, 
      new Baz { Foo = "C", Bar = 2 }, 
      new Baz { Foo = "D", Bar = 1 }, 
      new Baz { Foo = "D", Bar = 1 } 

     }; 

     // WANTED: An IEnumerable<Baz> that is like 

     // { Bar = 1, LoyalFoos = 2 }, (because both "B" and "D" are paired only with 1) 
     // { Bar = 2, LoyalFoos = 1 }, (because "C" is paired only with 2) 
     // { Bar = 3, LoyalFoos = 0 } (because there is no Foo that is paired only with the Bar 3) 


    } 

} 

有一個很好的方式與LINQ做到這一點?

+0

你能解釋一下更好的你想要什麼? 「配對」是什麼意思? –

+0

我認爲他的意思(如他的例子所示)「row1」中的對象有多少與 – Noctis

+0

有關@ThiagoCustodio我的意思是,「Baz」是一對(或之間的關係)a 'Foo'和一個'Bar' – Trumpster

回答

2

我不完全確定你想要輸出什麼。也許是這樣的,如果你正在尋找忠誠的Foo的每個欄數:

var result = bazzers 
     .Select(bazzer => bazzer.Bar) 
     .Distinct() 
     .Select(bar => new 
     { 
      Bar = bar, 
      LoyalFoos = bazzers 
       .GroupBy(bazzer => bazzer.Foo) 
       .Count(group => group.All(bazzer => bazzer.Bar == bar)) 
     }); 

或者,如果你希望每個忠實FOO給酒吧的分組:

var result = bazzers 
     .Select(bazzer => bazzer.Bar) 
     .Distinct() 
     .Select(bar => new 
     { 
      Bar = bar, 
      LoyalFoos = bazzers 
       .GroupBy(bazzer => bazzer.Foo) 
       .Where(group => group.All(bazzer => bazzer.Bar == bar)) 
       .SelectMany(group => group) 
     });