简体   繁体   中英

Remove items from one list that exist on another list

I have the following entity:

public class Media {
  public Int32 SourceId { get; set; }
  public String Key { get; set; } 
}

And I have dbContext.Medias and a list of Medias:

List<Media> medias = apiService.GetMedias(10);

I need the remove all items in medias which alreay exist in dbContext.Medias where two items are equal when SourceId && Key are equal. So I have:

medias = medias.Where(x => !dbContext.Medias.Any(y => y.Key == x.Id && y.SourceId == source.Id)).ToList();

The problem with this is that I am querying the database multiple times.

I would like to "invert" the solution which would become something like:

dbContext.Medias ...

Any idea of how can I do this?

string[] all = new string[]{"a", "b", "c", "d"}
string[] taken = new string[]{"a", "b"}
var remains = all.Except(taken);

In your case, you can use this:

List<Media> result = all.Except<Media>(taken).ToList<Media>();

Reference: What is the quickest way to remove one array of items from another?

May be something like (Not sure if everything is right)

var mediasFromDB = dbContext.Medias.Where(x=>medias.Any(y => x.Key == y.Id && x.SourceId == source.Id);

medias = medias.Where(x => !mediasFromDB.Any(y => y.Key == x.Id && y.SourceId == source.Id)).ToList();
List<String> media = new List<String> { "a", "b", "c" };
List<String> dbContext = new List<String> { "c", "d", "e" };

var resultset = dbContext.SelectMany(x => media.Where(y => y == x)).ToList(); //Distinct possible here if theres duplicate data ..
media = media.Where(e => resultset.All(r2 => e != r2)).ToList();

var res = media; // "a" , "b"
var resl = resultset; // "c"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM