How to merge two IQueryable lists

这一生的挚爱 提交于 2019-12-17 16:26:44

问题


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

IQueryable<MediaType> list1 = values;
IQueryable<MediaType> list2 = values1;
obj.Concat(obj1);

and

IQueryable<MediaType> list1 = values;
IQueryable<MediaType> list2 = values1;
obj.Union(obj1);

but if list1 is empty then the resultant list is also empty. In my case either list1 can be empty but list2 can have records. How should i merge them?


回答1:


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.




回答2:


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());



回答3:


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-



来源:https://stackoverflow.com/questions/4003813/how-to-merge-two-iqueryable-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!