Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two IQueryable lists

Tags:

c#

iqueryable

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?

like image 342
Fraz Sundal Avatar asked Oct 23 '10 11:10

Fraz Sundal


People also ask

What inherits from IQueryable?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed.

How do I add data to IQueryable?

The simple answer is that unless you add the record to the underlying datastore that the Iqueryable is querying, you can't add a new record into an IQueryable. So if you are using LinqToSql then you would have to add a row into the table that the IQueryable was querying in order to "add" a row into the IQueryable.

What is the difference between returning IQueryable vs IEnumerable?

The main difference between IEnumerable and IQueryable in C# is that IQueryable queries out-of-memory data stores, while IEnumerable queries in-memory data. Moreover, IQueryable is part of . NET's System. LINQ namespace, while IEnumerable is in System.

What is IQueryable C#?

IQueryable is suitable for querying data from out-memory (like remote database, service) collections. While querying data from a database, IQueryable executes a "select query" on server-side with all filters. IQueryable is beneficial for LINQ to SQL queries.


2 Answers

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.

like image 175
Jon Skeet Avatar answered Sep 19 '22 21:09

Jon Skeet


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()); 
like image 39
abatishchev Avatar answered Sep 17 '22 21:09

abatishchev