Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

reflection

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
}
like image 399
Lorry Laurence mcLarry Avatar asked Mar 31 '16 04:03

Lorry Laurence mcLarry


2 Answers

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);
like image 90
Steve Avatar answered Nov 17 '22 19:11

Steve


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  
}
like image 35
Hari Prasad Avatar answered Nov 17 '22 20:11

Hari Prasad