简体   繁体   English

C# - 检查列表是否包含属性等于值的对象?

[英]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
}

You don't need reflection, you can just use Linq: 你不需要反思,你可以只使用Linq:

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

If you need the object/s with that value, you can use Where : 如果您需要具有该值的object / s,则可以使用Where

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

You could do this using Linq extension method Any . 你可以使用Linq扩展方法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  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM