这是一个装饰问题,它只是语法糖,只是因为我想做。但基本上我有很多这样的代码......我正在使用 dynamic
纯粹为了节省时间和举例。
var terms = new List<string> {"alpha", "beta", "gamma", "delta", "epsilon", "rho"};
var list = new List<dynamic> {
new {
Foo = new List<string> {
"alpha",
"gamma"
}
}
};
var result = list
.Where(
n => n.Foo.Contains(terms[0]) ||
n.Foo.Contains(terms[1]) ||
n.Foo.Contains(terms[2]) ||
n.Foo.Contains(terms[3]) ||
n.Foo.Contains(terms[4]) ||
n.Foo.Contains(terms[5]))
.ToList();
显然,这纯粹是为了示例而荒谬的夸张,更准确的代码是......
Baseline =
Math.Round(Mutations.Where(n => n.Format.Is("Numeric"))
.Where(n => n.Sources.Contains("baseline") || n.Sources.Contains("items"))
.Sum(n => n.Measurement), 3);
但基本要点是我有很多地方想检查是否有 List<T>
(通常是 List<string>
,但有时可能会有其他对象。string
是我目前的重点)包含来自另一个 List<T>
的任何项目.
我认为使用 .Any()
会工作,但实际上我无法让它按预期运行。到目前为止,只有过度"||"
是产生正确结果的全部。
这在功能上很好,但写起来很烦人。我想知道是否有更简单的方法来写出来 - 扩展方法或 LINQ
也许我不明白的方法。
更新
我真的知道这可能是重复的,但我很难将问题的措辞弄清楚到我能找到的准确度> 重复。非常感谢任何帮助。
解决方案
非常感谢您提供的所有帮助。这是我完成的解决方案。我正在使用 dynamic
这里只是为了节省示例类的时间,但您提出的几个解决方案有效。
var terms = new List<string> {"alpha", "beta", "gamma", "delta", "epsilon", "rho"};
var list = new List<dynamic> {
new { // should match
Foo = new List<string> {
"alpha",
"gamma"
},
Index = 0
},
new { // should match
Foo = new List<string> {
"zeta",
"beta"
},
Index = 1
},
new { // should not match
Foo = new List<string> {
"omega",
"psi"
},
Index = 2
},
new { // should match
Foo = new List<string> {
"kappa",
"epsilon"
},
Index = 3
},
new { // should not match
Foo = new List<string> {
"sigma"
},
Index = 4
}
};
var results = list.Where(n => terms.Any(t => n.Foo.Contains(t))).ToList();
// expected output - [0][1][3]
results.ForEach(result => {
Console.WriteLine(result.Index);
});
最佳答案
I thought that using
.Any()
would work, but I actually haven't been able to get that to function as expected.
你应该能够通过将 Any()
应用于 terms
来使其工作,如下所示:
var result = list
.Where(n => terms.Any(t => n.Foo.Contains(t)))
.ToList();
关于c# - 在没有冗余 "||"命令的情况下,使用带有 WHERE 的 LINQ 来询问多个可能的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24264419/