C# 检查列表中的对象是否具有特定的字段内容
对不起,问题的标题,我真的不知道如何用一句话来解释它 我有一节这样的课C# 检查列表中的对象是否具有特定的字段内容,c#,list,C#,List,对不起,问题的标题,我真的不知道如何用一句话来解释它 我有一节这样的课 public class xyz { public static string attr1; public static string attr2; public static string attr3; } 如何检查列表中是否有attr1==“aaa”的对象 有类似的吗 List<xyz> MyList = new List<xyz>(); [...] bool att
public class xyz
{
public static string attr1;
public static string attr2;
public static string attr3;
}
如何检查列表中是否有attr1==“aaa”的对象
有类似的吗
List<xyz> MyList = new List<xyz>();
[...]
bool attr1_exist = MyList.attr1.Contains("aaa");
List MyList=new List();
[...]
bool attr1_exist=MyList.attr1.Contains(“aaa”);
?这应该可以做到:
bool attr1_exist = MyList.Exists(s=> s.attr1 == "aaa")
这应该做到:
bool attr1_exist = MyList.Exists(s=> s.attr1 == "aaa")
使用:
使用:
谢谢但是使用.Any或.Exists有什么区别呢?两者实际上都是相同的方法,.Any()可从.net 3.5及以上版本获得。我使用.NET2.0,所以建议Exists()是出于习惯。也许@DGibbs可以建议他为什么使用。有吗?@MichaelB几乎相同的原因,不过我使用的是更新版本的框架Any()
稍有不同,因为它可以在没有lambda的情况下使用,例如MyList。如果列表中有任何项,则Any()
将返回true,除此之外,它们基本相同。谢谢!但是使用.Any或.Exists有什么区别呢?两者实际上都是相同的方法,.Any()可从.net 3.5及以上版本获得。我使用.NET2.0,所以建议Exists()是出于习惯。也许@DGibbs可以建议他为什么使用。有吗?@MichaelB几乎相同的原因,不过我使用的是更新版本的框架Any()
稍有不同,因为它可以在没有lambda的情况下使用,例如MyList。如果列表中有任何项,则Any()
将返回true,除此之外,它们基本相同。