Appending/concatenating two IEnumerable sequences

后端 未结 4 1717
渐次进展
渐次进展 2020-12-15 15:01

I have two sets of datarows. They are each IEnumerable. I want to append/concatenate these two lists into one list. I\'m sure this is doable. I don\'t want to do a for loop

4条回答
  •  独厮守ぢ
    2020-12-15 16:00

    Assuming your objects are of the same type, you can use either Union or Concat. Note that, like the SQL UNION keyword, the Union operation will ensure that duplicates are eliminated, whereas Concat (like UNION ALL) will simply add the second list to the end of the first.

    IEnumerable first = ...;
    IEnumerable second = ...;
    
    IEnumerable combined = first.Concat(second);
    

    or

    IEnumerable combined = first.Union(second);
    

    If they are of different types, then you'll have to Select them into something common. For example:

    IEnumerable first = ...;
    IEnumerable second = ...;
    
    IEnumerable combined = first.Select(f => ConvertToT(f)).Concat(
                              second.Select(s => ConvertToT(s)));
    

    Where ConvertToT(TOne f) and ConvertToT(TTwo s) represent an operation that somehow converts an instance of TOne (and TTwo, respectively) into an instance of T.

提交回复
热议问题