Cguy23
Cguy23

Reputation: 33

Remove items from list that exist in another list

Both the following lists contain a QuoteID field. What is the best way to eliminate items from the currentQuotes list that have a QuoteID that exists in the quoteData list? Thanks.

  //Establish - Instantiate lists
  IList<QuotePaneView> currentQuotes = new List<QuotePaneView>();
  IList<Quote> quoteData = new List<Quote>();

  //Fill lists
  currentQuotes =  theQuotePaneService.GetAllQuotePanelStuff();
  quoteData =  theQuoteDataService.GetAllQuoteData();

Upvotes: 2

Views: 1174

Answers (2)

Mare Infinitus
Mare Infinitus

Reputation: 8162

A simple piece of Linq can help here:

Consider the following:

        var list1 = new List<int>();

        list1.Add(1);
        list1.Add(3);
        list1.Add(5);

        var list2 = new List<int>();

        list2.Add(1);
        list2.Add(2);
        list2.Add(3);

        var diff = list1.Except(list2);

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460058

You can use Except to get the set difference based on the ID. Then you only have to join the result(the unique ID's that are not in quoteData) to the currentQuotes list.

var notInQuoteData = currentQuotes.Select(q => q.QuoteID).Except(quoteData.Select(q => q.QuoteID));
var result = (from qUnique in notInQuoteData 
             join q in currentQuotes on qUnique equals q.QuoteID
             select q).ToList();

Upvotes: 1

Related Questions