重构foreach,如果是Linq

时间:2016-05-12 11:17:17

标签: c# linq

是否可以将所有给定的代码组合到linq,然后返回'true'或'false'?或者这样就好了吗?

如果可能,会有显着的性能差异吗?(数组和列表不会包含超过100个元素)

foreach (var item in myArray)
{
    if (myList.Exists(x => x.Value == item))
    {
        amountTrue++;
    }
}

if (myArray.Count() == amountTrue)
{
    isValid = true;
}

4 个答案:

答案 0 :(得分:11)

据我所见,该代码旨在检查

  

如果myArray的所有项目都在myExists

实施:

  isValid = myArray
    .All(item => myList.Exists(x => x.Value == item));

如果您想重构性能以及可读性,请查看瓶颈。比如说,myList.Exists减慢了吗?在这种情况下,请考虑HashSet<T>其中Tx.Value等类型。

答案 1 :(得分:7)

如果我理解了这个问题,你想知道列表中是否存在数组中的所有项目:

bool isValid = !myArray.Except(myList.Select (l => l.Value )).Any();

然后这将是一种有效的方法,因为Except在第一次丢失时使用了一组和Any次停止。

答案 2 :(得分:5)

不要重构性能,但可读性和可维护性。但是,有一个LINQ查询应该是高效的可读:

bool isValid = myArray.All(item => myList.Any(x => x.Value == item));

如果您还需要知道计数,您有多种选择:

例如Enumerable.Any

int amountTrue = myArray.Count(item => myList.Any(x => x.Value == item));
使用HashSet<T>

或更高效,假定string

var uniqueValues = new HashSet<string>(myList.Select(x => x.Value));
int amountTrue = myArray.Count(uniqueValues.Contains);

答案 3 :(得分:3)

这是LINQ实现

var res = ((from z in myArray
            where myList.Exists(x=>x.Value=z)
            select z).Count())==myArray.Count()