2013-02-22 94 views
2

我有一个列表,我想检查列表是否具有相同的值,即-1的所有整数数组。检查数组的列表是否具有相同的值

for ex。

int[] intk= {-1,-1,-1,-1,-1,-1}; 
int[] intl = { -1, -1, -1, -1, -1, -1 }; 
List<int[]> lst = new List<int[]>(); 
lst.Add(intk); 
lst.Add(intl); 

如何找到lst只有-1。

回答

4

拼合名单及SelectMany,然后检查是否所有相同:

int value = -1; 
bool allSame = lst.SelectMany(a => a).All(i => i == value); 
+1

+1:cause more * concrete * answer then mine。 – Tigran 2013-02-22 13:07:46

+0

@Tigran谢谢!你的答案对于单个阵列是正确的,但有问题的阵列列表 – 2013-02-22 13:08:36

+1

是的..那个工作..Thxs人!! .. – Raju 2013-02-22 13:12:04

0

您可以检查与使用LINQ捆绑.All(...)扩展方法。

为了创建与两个数组项,你应该使用.AddRange(...)List<T>T参数应该是int,而不是int[]列表:

int[] intk= {-1,-1,-1,-1,-1,-1}; 
int[] intl = { -1, -1, -1, -1, -1, -1 }; 
List<int> lst = new List<int>(); 
lst.AddRange(intk); 
lst.AddRange(intl); 

现在你就可以使用.All(...)

bool result = lst.All(item => item == 1); 

...或:

bool result = lst.All(item => item == -1); 
0

如果你想检查任何相同的值不仅是-1,这将工作。

var l = lst.SelectMany(_ => _); 
bool areSame = l.All(_ => l.FirstOrDefault() == _); 
相关问题