LINQ query Except does not work, List <long?> Vs. List <long>

What I'm trying to do is narrow down the results of the query, which I will use for subsequent binding. I want to get all the ProgramIds that are used in my gridview and remove them from the data source of my drop-down list (i.e. so that the user cannot create and insert an object in the gridview of the same ProgramId as the one that already exists)

Here is the code:

var query = from goals in DataContext.Goals select goals; var query2 = (from goals in query.AsEnumerable() select goals.ProgramId).ToList(); //List<long?> var query3 = (from progs in DataContext.Programs select progs.ProgramId).ToList(); //List<long> var cgps = query3.Except(query2); 

And I get these errors on var cgps = query3.Except(query2); :

Error 29 'System.Collections.Generic.List' does not contain a definition for 'Except' and the best extension overload method is 'System.Linq.ParallelEnumerable.Except (System.Linq.ParallelQuery, System.Collections.Generic. IEnumerable)' has some invalid arguments C: ... \ Shmeh \ Shmeh \ Shmeh \ this.aspx.cs 24 226 Project

Error 30 Instance argument: cannot convert from 'System.Collections.Generic.List' to 'System.Linq.ParallelQuery' C: ... \ Shmeh \ Shmeh \ Shmeh \ this.aspx.cs 24 226 Project

If you have an idea how to correctly do what I'm trying to do, any help would be greatly appreciated! Thanks!

+4
source share
6 answers

Except requires sequences to be of the same type. Try listing the long list to long? :

 var query3 = (from progs in DataContext.Programs select (long?)progs.ProgramId).ToList(); //List<long?> 
+8
source

Do you get this error because long? not the same type as long . Except requires that both enumerated objects have the same type.

What you can do is remove null values ​​from query2 and convert ProgramId to long

 var query2 = (from goals in query.AsEnumerable() where goals.ProgramId.HasValue select goals.ProgramId.Value).ToList() 
+5
source

to try

 var cgps = query3.Cast<long?>().Except(query2); 
+2
source
 var cgps = DataContext.Programs.Select(p => p.ProgramId) .Except(DataContext.Goals.Where(g => g.ProgramId.HasValue).Select(g => g.ProgramId.Value)); 
+1
source

I don't know if this will work for you.

 var query2 = (from goals in query.AsEnumerable() select goals.ProgramId).ToList() as List<long?>; var query3 = (from progs in DataContext.Programs select (long?)progs.ProgramId).ToList() as List<long?>; 
0
source

I do not know why he / she deleted his answer, but I use this:

 dropdownlist.DataSource = ( from progs in DataContext.Programs where !(from goals in query.AsEnumerable() select goals.ProgramId) .Contains(progs.ProgramId) select progs.Name).ToList(); dropdownlist.DataBind(); 

Since this does not require me to use several query variables, although the answer I accepted also worked with what I had.

0
source

All Articles