Lorry Laurence mcLarry
Lorry Laurence mcLarry

Reputation: 394

C# - check if list contains an object where a property equals value?

Is there a shorthand way to do it that does not involve loops?

public enum Item { Wood, Stone, Handle, Flint, StoneTool, Pallet, Bench  }

public struct ItemCount
{
    public Item Item;
    public int Count;
}

private List<ItemCount> _contents;

so something like:

if(_contents.Contains(ItemCount i where i.Item == Item.Wood))
{
    //do stuff
}

Upvotes: 10

Views: 22320

Answers (2)

Hari Prasad
Hari Prasad

Reputation: 16956

You could do this using Linq extension method Any.

if(_contents.Any(i=> i.Item == Item.Wood))
{
    // logic   
}

In case if you need a matching object, do this.

var firstMatch = _contents.FirstOrDefault(i=> i.Item == Item.Wood);

if(firstMatch != null)
{
    // logic   
    // Access firstMatch  
}

Upvotes: 6

Steve
Steve

Reputation: 9551

You don't need reflection, you can just use Linq:

if (_contents.Any(i=>i.Item == Item.Wood))
{
    //do stuff
}

If you need the object/s with that value, you can use Where:

var woodItems = _contents.Where(i=>i.Item == Item.Wood);

Upvotes: 19

Related Questions