我需要检查List是否包含指定的3以外的任何值。
实施例:
我有这个var sourceList = new List<string>("A", "B", "C", "D", "E");
,我想检查该列表是否包含任何值BESIDES“E”,“F”,“G”。只需一个Bool即可,sourceList
是用户选择的预定义列表的动态子集。我的BESIDES列表将是静态的。
谢谢,
答案 0 :(得分:6)
var flag = sourceList.Except(new[] { "E", "F", "G" }).Any();
答案 1 :(得分:5)
使用LINQ:
bool contains = sourceList.Any(t => (t != "E" && t != "F" && t != "G"));
答案 2 :(得分:3)
用户Except
和Any
扩展程序可以实现您的目标:
var sourceList = new List<string>{"A", "B", "C", "D", "E"};
var c = sourceList.Except( new List<string>{ "E", "F", "G"}).Any();
答案 3 :(得分:2)
var sourceList = new List<string>("A", "B", "C", "D", "E");
var checkList = new List<string>("E", "F", "G");
bool anyBesides = sourceList.Except(checkList).Any();
答案 4 :(得分:1)
不太可能使用Except
创建新列表,并且当前Any
解决方案无法重复用于不同的字母组合。
var sourceList = new List<string> { "A", "B", "C", "D", "E" };
var except = new[] { "E", "F", "G" };
var containsExcept = sourceList.Any(x => except.Contains(x));
答案 5 :(得分:0)
var sourceList = new List<string>{"A", "B", "C", "D", "E"};
bool res =sourceList.SequenceEqual(new string[] { "A", "B", "C"});
另外不要忘记没有你写过的构造函数:
var sourceList = new List<string>("A", "B", "C", "D", "E");
应该是:
var sourceList = new List<string>{"A", "B", "C", "D", "E"};
答案 6 :(得分:0)
var sourceList = new List<string>{"A", "B", "C", "D", "E"};
var besidesList = new List<string>{"E", "F", "G"};
var anyBesides = sourceList.Any(t => !besidesList.Contains(t));