Kevin Toet
Kevin Toet

Reputation: 367

Select 1 object from list with LINQ based on 2 vars

I've been trying to solve this by reading what was on StackOverflow and the information was quiet helpful but i can't seem to implement the things i found.

I have a data List and i want to check if an entry exists in the data set that match 2 variables i provide.

public void SaveWaveDataFor( List<WaveData> newData )
{
    foreach(WaveData wave in newData)
    {
        //WaveData item = data.FirstOrDefault( o => o.id == wave.id );
        var item = data.Select( o => new{ wave.id, wave.waveNumber  } );
        Debug.Log( item.id );
    }
}

Upvotes: 1

Views: 1800

Answers (3)

vijay
vijay

Reputation: 1353

If you just want to check whether entry exists or not then you can use Any Operator from Linq.

bool recordsExists = data.Any(o => o.id == matchId && o.waveNumber == matchNumber); 

Upvotes: 0

Maciej
Maciej

Reputation: 2185

The commented out line is better for this actually.

FirstOrDefault will return either the first matching item or null if no items match.

On the other hand, you could use Any() if you just want to know if an item exists. Any(x=>x.Id == matchId) will return true only if the list contains an item with a matching Id, false otherwise.

You would do it like this:

public void SaveWaveDataFor( List<WaveData> newData )
{
    int waveIdToMatch = 1;
    int waveNumberToMatch = 2;
    foreach(WaveData wave in newData)
    {
        WaveData item = data.FirstOrDefault( o => o.id == waveIdToMatch && o.waveNumber == waveNumberToMatch );
        //if a match exists, item will not be a WaveData object, otherwise it will be null
        Debug.Log( item.id );
    }
}

Upvotes: 0

Peter Gluck
Peter Gluck

Reputation: 8236

If you want to get all of the wave objects that match two criteria, you can use a Where() clause:

// items will be an IEnumerable<WaveData> containing the matching objects
// where id == matchId and waveNumber == matchNumber
var items = data.Where(o => o.id == matchId && o.waveNumber == matchNumber);

The Select() clause is typically used to transform the matching elements into objects of another type.

Upvotes: 1

Related Questions