【发布时间】:2017-07-07 10:35:23
【问题描述】:
我有两个列表
列表1 只有两个属性。 不能使用字典,因为可能有重复的键。 Property1 和 Property2 的组合是独一无二的。
public class List1
{
public string Property1 { get; internal set; }
public string Property2 { get; internal set; }
}
public class List2
{
public string Property1 { get; internal set; }
public string Property2 { get; internal set; }
public string Property3 { get; internal set; }
}
List<List1> mylist1 = new List<List1>() {
new List1() {Property1="664",Property2="Ford" },
new List1() {Property1="665",Property2="Ford" },
new List1() {Property1="664",Property2="Toyota" },
};
List<List2> mylist2 = new List<List2>() {
new List2() {Property1="664",Property2="Ford" ,Property3="USA"},
new List2() {Property1="665",Property2="Ford" ,Property3="USA"},
new List2() {Property1="664",Property2="Toyota" ,Property3="USA"},
new List2() {Property1="666",Property2="Toyota" ,Property3="USA"},
};
我需要获取 mylist1 和 mylist2 中的匹配项。匹配应该只发生在 Property1 和 Property2 上。比较时可以忽略 mylist2 中的 Property3。
目前我使用
var matchingCodes = mylist1.Where(l1 => mylist2.Any(l2 => (l2.Property1 == l1.Property1 && l2.Property2==l1.Property2))).ToList();
效果很好。但是有没有更好/最快的方法来做到这一点?
我可以将 List1 更改为任何其他类型。但不是 List2。
【问题讨论】:
-
来格式一致的缩进
-
LINQ 很少是性能最好的选项
标签: c# performance linq collections