What I am trying to do is combine two lists of different types into a new type, on the Id property of each. Both lists have different properties that I need in the new list.
This snippet is working already, but I am not happy with the performance. Assuming both lists are the same length, and in whatever order they need to be, is it possible to do this more efficiently?
class A
{
public int Id { get; set; }
public string stuffA { get; set; }
//other properties that we aren't using
}
class B
{
public int Id { get; set; }
public string stuffB { get; set; }
//other properties we aren't using
}
class C
{
public int Id { get; set; }
public string stuffA { get; set; }
public string stuffB { get; set; }
}
public List<C> getList(List<A> listA, List<B> listB)
{
var listC = new List<C>();
foreach(var a in listA)
{
var b = listB.Where(x => x.Id == a.Id);
listC.Add(new C{ Id = a.Id, stuffA = a.stuffA, stuffB = b.stuffB});
}
return listC;
}
I've looked into the Enumerable.Zip method, which pairs up two lists in the order provided, but I can't seem to use that with objects. The only examples I can make work are with primitive types.
I've seen this question: How merge two lists of different objects? but this doesn't create a new type, only an anonymous type containing the old lists (I believe).
Any ideas?