2016-04-25 81 views
1

得到兩班的十字路口,我有這個類如何基於財產

public class FlightSegment{ 
    public string ClassName { get;set;} 
} 

我想FlightSegments共同ClassName

void Main() 
{ 
    var list1 = new List<FlightSegment>() { 
     new FlightSegment{ ClassName = "A"}, 
     new FlightSegment { ClassName = "B"} 
    };  
    var list2 = new List<FlightSegment>() { 
     new FlightSegment{ ClassName = "B"}, 
     new FlightSegment { ClassName = "C"} 
    }; 

    var listOfLists = new List<List<FlightSegment>>() { list1, list2 };  
    var intersection = listOfLists.Aggregate((previousList, nextList) => previousList.Intersect(nextList).ToList());   
    Console.WriteLine(intersection); //Gives me empty result 

} 

我想是這樣的:

var intersection = listOfLists.Aggregate((previousList, nextList) => 
     previousList.Select(e=>e.ClassName).Intersect(nextList.Select(e=>e.ClassName)).ToList()); 

但給出錯誤:

Cannot convert expression type System.Collection.Generic.List<string> to return type System.Collection.Generic.List<FlightSegment> 

回答

4

您可以使用Intersect方法傳遞IEqualityComparer根據ClassName性能比較:

var list1 = new List<FlightSegment>() { 
    new FlightSegment{ ClassName = "A"}, 
    new FlightSegment { ClassName = "B"} 
};  
var list2 = new List<FlightSegment>() { 
    new FlightSegment{ ClassName = "B"}, 
    new FlightSegment { ClassName = "C"} 
}; 
var result = list1.Intersect(list2, new FlightComparer()); 

這僅返回包含集合:

class FlightComparer : EqualityComparer<FlightSegment> 
{ 
    public override bool Equals(FlightSegment x, FlightSegment y) 
    { 
     return x.ClassName == y.ClassName; 
    } 

    public override int GetHashCode(FlightSegment obj) 
    { 
     return obj.ClassName.GetHashCode(); 
    } 
} 

然後,使用該比較器進行交叉點一個元素FlightSegment { ClassName = "B" }

使用這個想法,並Aggregate,你可以根據屬性組列表的交集:

var intersection = listOfLists.Aggregate((previousList, nextList) => previousList.Intersect(nextList, new FlightComparer()).ToList()); 
+1

尼斯的答案。請注意文檔中的指導,「我們建議您從」EqualityComparer 「類派生而不是實現」IEqualityComparer 「接口,因爲」EqualityComparer 「類使用」IEquatable .Equals「方法測試相等性,而不是'Object.Equals'方法。「 –

+0

@JimMischel:謝謝,我會更新我的答案。 –

+0

有關通過實施IEqualityComparer 繼承EqualityComparer 的提示。 – jKlaus