C#-检查列表是否包含属性等于值的对象
本文关键字:于值 对象 属性 包含 检查 列表 是否 C#- | 更新日期: 2024-04-23 16:39:49
有没有一种不涉及循环的简写方法?
public enum Item { Wood, Stone, Handle, Flint, StoneTool, Pallet, Bench }
public struct ItemCount
{
public Item Item;
public int Count;
}
private List<ItemCount> _contents;
所以类似于:
if(_contents.Contains(ItemCount i where i.Item == Item.Wood))
{
//do stuff
}
您不需要反射,只需使用Linq:即可
if (_contents.Any(i=>i.Item == Item.Wood))
{
//do stuff
}
如果您需要具有该值的对象,可以使用Where
:
var woodItems = _contents.Where(i=>i.Item == Item.Wood);
您可以使用Linq
扩展方法Any
来完成此操作。
if(_contents.Any(i=> i.Item == Item.Wood))
{
// logic
}
如果您需要一个匹配的对象,请执行此操作。
var firstMatch = _contents.FirstOrDefault(i=> i.Item == Item.Wood);
if(firstMatch != null)
{
// logic
// Access firstMatch
}