2012-11-27 164 views
0

我有2個列表包含2種不同類型的對象。是否可以比較兩個列表中的對象並創建一個包含具有匹配屬性值的對象的新列表?從2個現有列表創建新列表,其中有匹配的值

例如,如果我有一個巴士(帶有一個屬性'busID')和一個驅動程序列表(也帶有一個屬性'busID')列表。我可以在哪裏創建一個新的列表(buses.busesID = drivers.busID)?

我意識到這個問題很模糊,並且不包含任何示例代碼。儘管如此,我仍然陷入困境。

+0

功課?如果是這樣,請將其標記爲這樣。 –

+0

和什麼新的列表?公交車?驅動程序?或每個元組? – Enigmativity

+0

@ChristopherEstep「家庭作業」標籤已被棄用,不應再使用。 –

回答

0

試試這個:

var query = 
    from driver in drivers 
    join bus in buses on driver.busID equals bus.busID 
    select new { driver, bus }; 

var results = query.ToList(); 
1

您可以使用LINQ加入這些兩個集合在這個ID,產生例如總線及其驅動程序的元組。使用LINQ語法,它應該是這樣的:

var result = from bus in buses 
      join driver in drivers on bus.busID equals driver.busID 
      select new { Bus = bus, Driver = driver } 

這可能會引入一些新的功能對你來說,就像LINQ本身,或anonymous type定義。

結果是一個查詢,該查詢懶惰地執行併產生一組總線+驅動程序對。

+0

我正在尋找'分配'司機到公共汽車。我認爲這將是一個簡單的解決方案,列出將使用某個總線的所有驅動程序。這種方法可以正常工作,或者您知道更優雅的解決方案嗎? – user1769279

+0

看看其他的LINQ方法,他們提供了很多方法來查看集合 - 你可以過濾它們,項目項目,聚合項目...如果你想列出指定總線的驅動程序,這是一個簡單的過濾器('Where'方法/子句)。 ** [101 LINQ示例](http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b)**在開始的時候給了我很多幫助。 –

+0

非常感謝幫助的人!我怎樣才能將這個查詢的結果元組添加到可以在WinForms列表框中顯示的列表中? – user1769279

0

如果你是在一個更抽象的解決方案之後,那麼你可以使用反射。

class A 
    { 
     public int x { get; set; } 
     public int y { get; set; } 
    } 

    class B 
    { 
     public int y { get; set; } 
     public int z { get; set; } 
    } 

    static List<A> listA = new List<A>(); 
    static List<B> listB = new List<B>(); 

    static void Main(string[] args) 
    { 
     listA.Add(new A {x = 0, y = 1}); 
     listA.Add(new A {x = 0, y = 2}); 
     listB.Add(new B {y = 2, z = 9}); 
     listB.Add(new B {y = 3, z = 9}); 

     // get all properties from classes A & B and find ones with matching names and types 
     var propsA = typeof(A).GetProperties(); 
     var propsB = typeof(B).GetProperties(); 
     var matchingProps = new List<Tuple<PropertyInfo, PropertyInfo>>(); 
     foreach (var pa in propsA) 
     { 
      foreach (var pb in propsB) 
      { 
       if (pa.Name == pb.Name && pa.GetType() == pb.GetType()) 
       { 
        matchingProps.Add(new Tuple<PropertyInfo, PropertyInfo>(pa, pb)); 
       } 
      } 
     } 

     // foreach matching property, get the value from each element in list A and try to find matching one from list B 
     var matchingAB = new List<Tuple<A, B>>(); 
     foreach (var mp in matchingProps) 
     { 
      foreach (var a in listA) 
      { 
       var valA = mp.Item1.GetValue(a, null); 

       foreach (var b in listB) 
       { 
        var valB = mp.Item2.GetValue(b, null); 

        if (valA.Equals(valB)) 
        { 
         matchingAB.Add(new Tuple<A, B>(a, b)); 
        } 
       } 
      } 
     } 

     Console.WriteLine(matchingAB.Count); // this prints 1 in this case 
    } 

旁註:元組是一個.NET 4類,如果不能使用,那麼你可以很容易地編寫自己:Equivalent of Tuple (.NET 4) for .NET Framework 3.5

相關問題