是否有可能将所有给定的代码组合到linq,然后返回'true'或'false'?或者它是这样的好吗?
如果可能,是否会有显着的性能差异?(数组和列表不会包含超过100个元素)
foreach (var item in myArray)
{
if (myList.Exists(x => x.Value == item))
{
amountTrue++;
}
}
if (myArray.Count() == amountTrue)
{
isValid = true;
}
Run Code Online (Sandbox Code Playgroud)
Dmi*_*nko 11
据我所知,该代码旨在检查
如果所有的项目
myArray都在myExists
实施:
isValid = myArray
.All(item => myList.Exists(x => x.Value == item));
Run Code Online (Sandbox Code Playgroud)
如果您想重构性能以及可读性,请查看瓶颈.说,它myList.Exists减慢了吗?在那种情况下,想想HashSet<T>哪里T是一种类型x.Value等.
小智 7
如果我理解了这个问题,你想知道列表中是否存在数组中的所有项:
bool isValid = !myArray.Except(myList.Select (l => l.Value )).Any();
Run Code Online (Sandbox Code Playgroud)
那么这将是一种有效的方法,因为Except使用一个集合并Any在第一次丢失时停止.
不要重构性能,而是可读性和可维护性.但是,有一个LINQ查询应该是高效和可读的:
bool isValid = myArray.All(item => myList.Any(x => x.Value == item));
Run Code Online (Sandbox Code Playgroud)
如果您还需要知道计数,您有多种选择:
例如Enumerable.Any:
int amountTrue = myArray.Count(item => myList.Any(x => x.Value == item));
Run Code Online (Sandbox Code Playgroud)
或更有效的HashSet<T>假设string:
var uniqueValues = new HashSet<string>(myList.Select(x => x.Value));
int amountTrue = myArray.Count(uniqueValues.Contains);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
205 次 |
| 最近记录: |