C# 使用linq从不同类型的目标集合中的源集合中查找特定值
我想知道分号后的sourceList值是否包含在Name属性标识的targetList中。如果这是真的,则必须返回布尔值 它不工作,但我尝试了一些 我猜我的linq不正确。所有的事情 “FoundSomething”包含在targetList中,因此它应该返回TRUEC# 使用linq从不同类型的目标集合中的源集合中查找特定值,c#,linq,C#,Linq,我想知道分号后的sourceList值是否包含在Name属性标识的targetList中。如果这是真的,则必须返回布尔值 它不工作,但我尝试了一些 我猜我的linq不正确。所有的事情 “FoundSomething”包含在targetList中,因此它应该返回TRUE var sourceList = new String[] { "1;HideButton", "2;ShowButton", "3;HideButton", "4;ShowButton",
var sourceList = new String[]
{
"1;HideButton",
"2;ShowButton",
"3;HideButton",
"4;ShowButton",
"5;HideButton",
"6;ShowButton",
"7;HideButton",
"8;ShowButton",
"9;HideButton",
"10;FoundSomething",
};
var targetList = new List<GlobalConfiguration>()
{
new GlobalConfiguration{ Name = "444" },
new GlobalConfiguration{ Name = "fdsdffd" },
new GlobalConfiguration{ Name = "44" },
new GlobalConfiguration{ Name = "fsdd" },
new GlobalConfiguration{ Name = "fs4rtref" },
new GlobalConfiguration{ Name = "ftrtras" },
new GlobalConfiguration{ Name = "FoundSomething" },
};
Boolean exists = sourceList.Any(a => targetList.All(c => c.Name == a.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Last()));
var sourceList=新字符串[]
{
“1;隐藏按钮”,
“2;显示按钮”,
“3;隐藏按钮”,
“4;显示按钮”,
“5;隐藏按钮”,
“6;显示按钮”,
“7;隐藏按钮”,
“8;显示按钮”,
“9;隐藏按钮”,
“10;找到什么”,
};
var targetList=新列表()
{
新的全局配置{Name=“444”},
新的全局配置{Name=“fdsdffd”},
新的全局配置{Name=“44”},
新的全局配置{Name=“fsdd”},
新的全局配置{Name=“fs4rtref”},
新的全局配置{Name=“ftrtras”},
新的全局配置{Name=“FoundSomething”},
};
Boolean exists=sourceList.Any(a=>targetList.All(c=>c.Name==a.Split(new[]{';'},StringSplitOptions.removemptyentries.Last());
我不能100%肯定我理解你的目标,但这里是我最好的猜测:
sourceList
.Select(x => x.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Last())
.Intersect(targetList.Select(x => x.Name))
.Any();
它的作用是创建两个序列
源列表的后半部分(分号后)
targetList的name属性
选择
然后它使用Intersect
返回两个序列共享的任何项
最后,它使用Any
确定是否从Intersect
返回了任何内容(我认为这很容易理解)。看起来您需要另一个Any
而不是All
:
bool exists = sourceList
.Select(s => s.Split(new[] { ';' }, StringSplitOption.RemoveEmptyEntries).Last())
.Any(v => targetList.Any(t => s == t.Name));
你基本上有两个集合,你想看看它们的交点是否为空。多亏了方便的扩展方法,您应该这样做
var source = sourceList.Select(s=>s.Split(';')[1]);
var target = targetList.Select(t=>t.Name);
return source.Intersect(target).Count() > 0;
啊,是的,我想了想,但是没有按照这个想法去做。谢谢您的代码工作正常,我更喜欢它而不是Christophers解决方案,因为它的一个linq方法调用更少。您应该使用Any
而不是Count()>0。它将简化电路,更能描述代码的目标