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?
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.
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.
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.
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.
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
.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With