Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat two Ienumerables of different types

Tags:

c#

I have two instances of IEnumerable<T> (with the Different T). I want to combine both of them .

  1. IEnumerable<ClassA>

  2. IEnumerable<ClassB>

Both in CLass A and ClassB i have one common property .Lets say for example it is EmpId ..

Is there a build-in method in .Net to do that or do I have to write it myself?

like image 486
user3543884 Avatar asked Mar 19 '23 03:03

user3543884


2 Answers

Assuming you can extract the common property to a common interface, let's say IEmployee, then you could just Cast() and then Concatenate the collections:

classAItems.Cast<IEmployee>().Concat(classBItems)

Note that this will only iterate over those IEnumerables on demand. If you want to create a List containing the content of both sequences at the time you combined them, you can use ToList():

List<IEmployee> all = classAItems.Cast<IEmployee>().Concat(classBItems).ToList();

You can do the same if you only need an array using ToArray().

like image 91
Botz3000 Avatar answered Mar 21 '23 15:03

Botz3000


You can get the concatenated common property easily enough:

var empIds = first.Select(x => x.EmpId).Concat(second.Select(x => x.EmpId));

If this is not what you are after, you will have to be more specific.

like image 33
Marc Gravell Avatar answered Mar 21 '23 17:03

Marc Gravell