67

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Fraz Sundal
  • 10,288
  • 22
  • 81
  • 132

3 Answers3

99

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Can the elements in an IQuerable be ordered? If so, do both of these statements preserve the order in the same way? – CowboyBebop Feb 10 '15 at 16:40
  • 1
    @CowboyBebop: They *can* be ordered - `IOrderedQueryable` extends `IQueryable`, for example. In LINQ to Objects, the order is preserved with these operations - but I doubt that it's guaranteed for out-of-process query providers. – Jon Skeet Feb 10 '15 at 17:08
  • Interesting part is you can still chain the query using Union, so it wont be executed and the result would still be an `IQueryable` which helped me alot in my case. – Niklas Sep 19 '17 at 07:11
  • Hello, when I use this codes for IQueryable methods it shows error that result is wrong. iq1 = db.MyModel.Where(m => m.CategoryId == 1); and iq2 = db.MyModel.Where(m => m.CategoryId==2); then iqResult = iq1.Concat(iq2); when I debug in this line I get error. – A Programmer May 24 '18 at 03:56
  • 1
    @AProgrammer: I suggest you ask a new question with much more detail than "I get error". – Jon Skeet May 24 '18 at 05:54
6

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());
abatishchev
  • 98,240
  • 88
  • 296
  • 433
-2

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-

Red
  • 634
  • 6
  • 15