Reputation: 1817
I have two lists. List<A>
, where the type A
has two properties { x, y } and List<B>
where the type B
has two properties { y, z }.
I want to join the two lists on y and then pick x and z in my new list.
Is this possible using some a LINQ one-liner?
Upvotes: 2
Views: 1325
Reputation: 8743
I assume you have two types:
class A
{
public int x {get; set;}
public int y {get; set;}
}
class B
{
public int y {get;set;}
public int z {get;set;}
}
And your two lists:
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}};
You can join them with LINQ:
var joined = a.Join(b, a => a.y, b => b.y, (a,b) => new {a.x, b.z}).ToList();
You will have a List with two items: x=1, z=2 and x=2, z=3.
Upvotes: 4
Reputation: 26362
You are looking for linq Union
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
*/
Your case dotnetfiddle:
string[] ints1 = { "x", "y" };
string[] ints2 = { "y", "Z" };
IEnumerable<string> union = ints1.Union(ints2);
foreach (string num in union)
{
Console.Write("{0} ", num);
}
Upvotes: 1