我有一个可变数量的列表对象,我需要比较其中相同索引处的值。列表中的条目数量是给定的,不会改变。
例如:4列出每4个条目
所以我在这个例子中寻找的是4个布尔值,每个索引一个。获取不匹配条目的索引也很好。
伪:
bool isFirstEqual = (list1[i] == list2[i] == list3[i] == list4[i]);但我需要以一种适用于数量可变的列表的方式来完成此操作。我可以有6个列表,也可以有2个。
我正在考虑用LINQs .Except()做一些事情,但是不确定如何在列表数量可变的情况下使用它。
我正在努力寻找一个优雅的解决方案,我确信它就在那里。在这方面的任何帮助都是非常感谢的。
发布于 2018-05-31 16:05:21
bool AreIndexesEqual(int index, List<List<int>> lists)
{
int match = lists[0][index];
foreach(List<int> list in lists.Skip(1))
{
if (list[index] != match)
{
return false;
}
}
return true;
}发布于 2018-05-31 16:22:25
举个例子:
List<List<int>> listOfLists = new List<List<int>>
{
new List<int> { 1, 100, 2},
new List<int> { 2, 100, 3},
new List<int> { 3, 100, 4},
new List<int> { 4, 100, 5},
};So a List<> of List<int>
返回List<bool>的完全不可读的LINQ表达式类似于:
List<bool> result = Enumerable.Range(0, listOfLists.Count != 0 ? listOfLists[0].Count : 0)
.Select(x => listOfLists.Count <= 1 ?
true :
listOfLists.Skip(1).All(y => y[x] == listOfLists[0][x])
).ToList();这里我想向你展示,如果你对任何问题的第一个解决方案是LINQ,那么现在你可能会有两个问题。
现在..。这个linq是做什么的?我们有4个List<int>,每个都有3个元素...所以3行4列。我们想要“按行”计算结果,所以第一件事是发现行数,也就是listOfLists[0].Count (我们对有0行的情况进行了预检查)。现在,我们使用Enumerable.Range(0, numberofrows) (如for (int i = 0; i < numberofrows; i++) )生成索引(如for)。对于每一行,我们查看是否有0或1列(listOfLists.Count <= 1),则结果为true,否则我们将所有其他列y[x]与第一列listOfLists[0][x]进行比较。
使用双for周期,可能会变得更加清晰:
var result2 = new List<bool>(listOfLists.Count != 0 ? listOfLists[0].Count : 0);
// Note the use of .Capacity here. It is listOfLists.Count != 0 ? listOfLists[0].Count : 0
for (int col = 0; col < result2.Capacity; col++)
{
if (listOfLists.Count <= 1)
{
result2.Add(true);
}
else
{
bool equal = true;
for (int row = 1; row < listOfLists.Count; row++)
{
if (listOfLists[row][col] != listOfLists[0][col])
{
equal = false;
break;
}
}
result2.Add(equal);
}
}注意,这两个程序都可以简化为:new int[0].All(x => something) == true,因此空IEnumerable<>上的.All()为true。您可以删除直到else关键字的listOfLists.Count <= 1 ? true :和if (...) { ... } else,只保留else中的代码
var result2 = new List<bool>(listOfLists.Count != 0 ? listOfLists[0].Count : 0);
// Note the use of .Capacity here. It is listOfLists.Count != 0 ? listOfLists[0].Count : 0
for (int col = 0; col < result2.Capacity; col++)
{
bool equal = true;
for (int row = 1; row < listOfLists.Count; row++)
{
if (listOfLists[row][col] != listOfLists[0][col])
{
equal = false;
break;
}
}
result2.Add(equal);
}发布于 2018-05-31 17:00:17
这就是你要的
IEnumerable<bool> CompareAll<T>(IEnumerable<IEnumerable<T>> source)
{
var lists = source.ToList();
var firstList = lists[0];
var otherLists = lists.Skip(1).ToList();
foreach(var t1 in firstList)
{
yield return otherlists.All(tn => tn.Equals(t1));
}
}https://stackoverflow.com/questions/50619357
复制相似问题