Lambda多个条件来验证对象列表中的列表?
问题描述:
我有以下项目Lambda多个条件来验证对象列表中的列表?
List<person> lst = new List<person>()
lst.Add(new person(){ name="abc", age="24" });
lst.Add(new person(){ name="xyz", age="25" });
lst.Add(new person(){ name="zxc", age="28" });
lst.Add(new person(){ name="wer", age="38" });
List<string> strlst = new List<string>();
strlst.Add("abc");
strlst.Add("zxc");
现在我确认名单
lst.Exists(a => strlst.Contains(a.name))
我如何验证整个列表,如果它包含“ABC and
xyz`两者组成的列表?
答
纠正我,如果我错了,但我相信你的本意是验证对你lst
变量,而不是strlst
。如果是strlist
,那么我相信@ LosManos的答案是一个非常好的方法。如果你想验证List<person> lst
与strlst
的值,那么你应该做到以下几点:
var allNames = lst.Select(l => l.name);
var containsAll = strlist.All(s => allNames.Contains(s));
这种方式也将确保你能做到这一点正确的,即使你有两个以上的东西,你需要比较上。
答
如果您发现两个名称中的Intersect
,您将得到两个列表的共同名称。如果该交叉点与您的字符串列表大小相同,则意味着它们都位于交叉点中,这意味着它们都在另一个列表中。
return list.Select(person => person.name)
.Intersect(strlst).Count() == strlst.Count();
+0
感谢其为我服务的服务.. – Pravin 2013-02-21 15:09:50
请注意,这是一个相当低效的操作,因为您正在为您搜索的每个字符串执行所有人员的线性搜索,所以它不能很好地适用于大数据集。对于小数据集,它会很好。 – Servy 2013-02-21 14:54:40
你能提出任何其他方法吗? – Pravin 2013-02-21 15:05:14
@Pravin当然,请看我的答案。 – Servy 2013-02-21 15:08:39