我有两个列表。 List<A>
,其中类型 A
有两个属性 { x, y } 和 List<B>
,其中类型 B
有两个属性 { y, z }。
我想加入 y 上的两个列表,然后在我的新列表中选择 x 和 z。
这可以使用一些 LINQ one-liner 吗?
答案 0 :(得分:4)
我假设您有两种类型:
class A
{
public int x {get; set;}
public int y {get; set;}
}
class B
{
public int y {get;set;}
public int z {get;set;}
}
还有你的两个列表:
List<A> a = new List<A> { new A { x = 1, y = 2 }, new A { x= 2, y = 3}};
List<B> b = new List<B> { new B { y = 2, z = 2 }, new B { y= 3, z = 3}};
您可以使用 LINQ 加入他们:
var joined = a.Join(b, a => a.y, b => b.y, (a,b) => new {a.x, b.z}).ToList();
您将拥有一个包含两个项目的列表:x=1, z=2 和 x=2, z=3。
答案 1 :(得分:1)
您正在寻找 linq this
int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };
int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };
IEnumerable<int> union = ints1.Union(ints2);
foreach (int num in union)
{
Console.Write("{0} ", num);
}
/*
This code produces the following output:
5 3 9 7 8 6 4 1 0
*/
你的情况Union:
string[] ints1 = { "x", "y" };
string[] ints2 = { "y", "Z" };
IEnumerable<string> union = ints1.Union(ints2);
foreach (string num in union)
{
Console.Write("{0} ", num);
}