Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - Except one list with items in another

Tags:

c#

linq

I think my question is easy, but I'm a newbie in linq... So I'm having a hard time here

My system calls a service, called serviceTOP, that returns me a list of itemTOP {Id, Name}.

These ItemsTOP aren't in my system, but the user can choose which itemTOP to import to the system.

The imported ItemsTOP becomes an object Item { Id, IdTOP, Name }

So, when the system calls serviceTOP, before showing them to the user, I must filter the already imported items from the list.

Let's go to code:

IList<ItemsTOP> listTOP = new ServiceTOP().GetItemsTOP();

IList<Items> list = new WCFServiceClient().GetItems();

var filteredListTOP = listTOP.Select( i => i.Id ).Except( i => i.IdTOP );

This kind of works, but it returns a list of strings containing only the id.

I'd like to select both id and name of the TOP.

like image 401
Ortiga Avatar asked Apr 11 '11 18:04

Ortiga


People also ask

How Except works in LINQ?

The Except() method requires two collections. It returns a new collection with elements from the first collection which do not exist in the second collection (parameter collection). Except extension method doesn't return the correct result for the collection of complex types.

Where and Except LINQ C#?

What is LINQ Except in C#? The LINQ Except Method in C# is used to return the elements which are present in the first data source but not in the second data source. There are two overloaded versions available for the LINQ Except Method as shown below.

How use contains in LINQ?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.

What does Except do in C#?

The Except operator returns the set difference. Or in other words, we can say that it returns the set or collection which contain the elements that do not appear in the second collection or set. It does not support Query Syntax in C# and VB.Net languages.


1 Answers

Change this:

listTOP.Select(i => i.Id )
       .Except( i => i.IdTOP );

To this:

listTOP.Select(i => new { ID = i.id, Name = i.Name} )
       .Except( i => i.IdTOP );
like image 139
Only Bolivian Here Avatar answered Sep 28 '22 10:09

Only Bolivian Here