有没有一种简单的方法可以做到不涉及循环?
public enum Item { Wood, Stone, Handle, Flint, StoneTool, Pallet, Bench }
public struct ItemCount
{
public Item Item;
public int Count;
}
private List<ItemCount> _contents;
Run Code Online (Sandbox Code Playgroud)
像这样的东西:
if(_contents.Contains(ItemCount i where i.Item == Item.Wood))
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
你可以使用Linq扩展方法来做到这一点Any。
if(_contents.Any(i=> i.Item == Item.Wood))
{
// logic
}
Run Code Online (Sandbox Code Playgroud)
如果您需要匹配的对象,请执行此操作。
var firstMatch = _contents.FirstOrDefault(i=> i.Item == Item.Wood);
if(firstMatch != null)
{
// logic
// Access firstMatch
}
Run Code Online (Sandbox Code Playgroud)
你不需要反思,你可以只使用Linq:
if (_contents.Any(i=>i.Item == Item.Wood))
{
//do stuff
}
Run Code Online (Sandbox Code Playgroud)
如果您需要具有该值的object/s,您可以使用Where:
var woodItems = _contents.Where(i=>i.Item == Item.Wood);
Run Code Online (Sandbox Code Playgroud)