Barry Michael Doyle
Barry Michael Doyle

Reputation: 10598

Get a List of results where items != already existing items

I am developing an asp.net application and I have the following list:

public static List<SelectedSongKey_List> SelectedSongKeys(int songId)
{
    var db = new BMDWorshipEntities();
    var results = (from x in db.Keys
                   where x.SongId == songId
                   select x.ChordKey).ToList();

    var sortingOrder = new List<string>()
    {
        "Ab", "A", "Bb", "B", "C", "C#", "Db", "D", "Eb", "E", "F", "F#", "Gb", "G"
    };

    results = results.OrderBy(x => sortingOrder.IndexOf(x)).ToList();

    var skList = new List<SelectedSongKey_List>();
    foreach(var sk in results)
    {
        skList.Add(new SelectedSongKey_List()
        {
            SongKey = sk.Trim()
        }); 
    }

    return skList;
}

This list will populate a drop-down list with all the existing ChordKeys:

Now I would like to make another List containing all the ChordKeys (Chords are in the sortingOrder) that don't exist on the db yet.

What results statement can I write in order to do that?

Upvotes: 3

Views: 210

Answers (3)

Geek Josh
Geek Josh

Reputation: 393

You could use a lambda Where statement on sortingOrder to return only those values not contained in results:

var newChords = sortingOrder.Where(c => return !results.Contains(c));

EDIT: will leave this here for posterity, but Richa Garg's answer is easier to read.

Upvotes: 0

Phillip Ngan
Phillip Ngan

Reputation: 16106

Start with the sortingOrder and keep only items not already in results.

    var notInDb = sortingOrder.Where(item => !results.Contains(item));

Upvotes: 0

Richa Garg
Richa Garg

Reputation: 1926

You can use the Except Clause

var exceptedList = sortingOrder.Except(results).ToList();

Upvotes: 8

Related Questions