How to merge two IQueryable lists

前端 未结 3 592
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 13:36

I want to merge the records of two IQueryable lists in C#. I try

IQueryable list1 = values;
IQueryable list2 = values1;
ob         


        
相关标签:
3条回答
  • 2020-12-03 13:46

    Even

    var result = Enumerable.Concat(list1, list2);
    

    doesn't work?

    And be sure that lists are empty, not null:

    var result = Enumerable.Concat(
        list1 ?? Enumerable.Empty<MediaType>()
        list2 ?? Enumerable.Empty<MediaType>());
    

    Also try:

    var result = Enumerable.Concat(
        list1.AsEnumerable(),
        list2.AsEnumerable());
    
    0 讨论(0)
  • 2020-12-03 13:47

    You're not using the return value - just like all other LINQ operators, the method doesn't change the existing sequence - it returns a new sequence. So try this:

    var list3 = list1.Concat(list2);
    

    or

    var list4 = list1.Union(list2);
    

    Union is a set operation - it returns distinct values.

    Concat simply returns the items from the first sequence followed by the items from the second sequence; the resulting sequence can include duplicate items.

    You can think of Union as Concat followed by Distinct.

    0 讨论(0)
  • 2020-12-03 13:57

    Another option I found:
    Declare:
    IEnumerable<int> usersIds = new int[0];
    For example inside a loop:

    foreach (var id in Ids) {
                IQueryable<int> _usersIds = bl.GetUsers(id).Select(x => x.UserID);
                usersIds = usersIds.Concat(_usersIds);
            }  
    var ids = usersIds.Distinct();
    

    Now usersIds and ids(as distinct) contains the id of all users as IEnumerable -int-

    0 讨论(0)
提交回复
热议问题