Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return values from list that are not present in another list using LinQ

Hey i have list of integers which are id’s.
I want to create async method that returns list of id’s that are not present in dbContext table. I have something like this.

public async Task<List<int>> NotExisting(List<int> inputIds, CancellationToken cancellationtoken)
{
var notExisting = await _dbContext.Table
    .Where(x => !inputIds.Contains(x.Id)).Select(x => x.Id).ToListAsync();

return notExisting;
}

Now its just taking all of the elements in table that doesnt match the input id. I want to only get the elements from inputIds that are not present in _dbContext.Table. I know i am taking wrong thing in Select but i dont know how to access the current id in inputIds.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need to switch the SELECT source, since the IDs you want to have are ultimately NOT coming from the database:

var allIDsInDb = (await _dbContext.Table.Select(x => x.Id).ToListAsync()).ToHashSet();
// ToHashSet() was for faster lookups in the next line
var notExisting = inputIds.Except(allIDsInDb).ToList();

UPD: If you don’t want to pull all the IDs from the database, you still need to find out which IDs from your list DO exist in the db, so just add a condition:

var allIDsInDb = (await _dbContext.Table.Where(x => inputIds.Contains(x.Id)).Select(x => x.Id).ToListAsync()).ToHashSet();
// ToHashSet() was for faster lookups in the next line
var notExisting = inputIds.Except(allIDsInDb).ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading