例如:
{1, 1, 11, 1111, 1111111}
此数组有效,因为每个元素仅使用数字1。
{11, 101, 1111, 11111}
此数组无效,因为每个元素使用0和1位数。
答案 0 :(得分:4)
您可以尝试这样的事情:
var isValid = arr
.Select(a => a.ToString()) //Call .ToString() on each integer
.SelectMany(a => a) //Select each character in the string and flatten
.Distinct() //Get only the unique characters
.Count() <= 1; //If there are more than 1 unique characters, it's invalid.
答案 1 :(得分:3)
试试这个:
var allSame = source.SelectMany(n => n.ToString()).Distinct().Count() == 1;
这为您的两个输入提供了正确的结果。
答案 2 :(得分:1)
无效 = {111,222,333},{111,110,101}。 有效 = {111,111},{222,222}
char c = arr[0].ToString()[0]; //get the first digit to compare
//char c = arr.First().ToString().First()
bool isValid = arr
.SelectMany(i => i.ToString()) //select all digits as chars
.All(s => s == c); //compare them to the c char
仅使用LINQ(性能不佳)
bool isValid = arr
.SelectMany(i => i.ToString()) //select all digits as chars
.All(s => s == arr.First().ToString().First()); //compare them to the c char
第二个示例将为IEnumerable<Char>
(效果不佳)的每个数字创建Array
无效 = {111,110,101}。 有效 = {111,111},{222,222}, {111,222,333}
bool isValid = arr
.SelectMany(i => i.ToString())
.Distinct()
.Count() == 1