Reputation: 1395
I want to check the elements in an array. If all elements except the first one are empty, then print out the array.
I am using the linq " Are all elements Empty function ". I'm not sure this is the correct syntax.
bool a = items.All(element => element == "");
Here is my code, it is not catching the Line 4 which is a a target line to identify of the commented lines.
private void CheckForQualifyArray(string line)
{
// "COMBINED ACCUMULATED TOTALS","","","","","","FINAL RESULTS",
// "Primary Election","","","","","61 Of 61 Vote Centers Reporting","",
// "March 3, 2020","","","","","","Collin County",
// "1","","","","","","",
// "STATISTICS","","","","","","",
// "","TOTAL","Election Day","Early Voting","Mail","","",
string[] input = line.Split(',');
int arraySize = input.Length - 1;
string[] items = new string[arraySize];
items[0] = input[1].ToString();
items[1] = input[2].ToString();
items[2] = input[3].ToString();
items[3] = input[4].ToString();
items[4] = input[5].ToString();
items[5] = input[6].ToString();
items[6] = input[7].ToString();
// Are all elements Empty
bool a = items.All(element => element == "");
if (a)
{
Debug.WriteLine(line);
}
}
Upvotes: 1
Views: 435
Reputation: 23228
You don't need to create a new array, just use Skip
method to omit the first element from array of line
items and then use All
. ToString()
call is also redundant in your code, because input
is already an array of strings
You can also use IsNullOrEmpty
method to check that string is empty instead of comparison with empty string
string[] input = line.Split(',');
// Are all elements Empty
bool a = input.Skip(1).All(element => string.IsNullOrEmpty(element));
If quotes itself represent a part of string (it seems so), then All
method predicate should care about the quotes (not the empty string)
bool a = input.Skip(1).All(element => element == @"""");
Upvotes: 3
Reputation: 18155
You could use Linq as the following
var input = line.Split(',').ToList();
if(input.Skip(1).All(x=>x.Equals("\"\""))) // Condition based on note below
{
Debug.WriteLine(line);
}
Enumerable.Skip
allows you to skip/bypass the required number of elements, and returns the remaining elements. You could then use Enumerable.All
for checking the required condition.
Note Based on Samples in OP
Based on the samples lines given in the question, it is unclear whether you want to check if the string is Empty
or ""
(Quotes are part of string).
In case you want to check for String.Empty
you could modify your condition above as
if(input.Skip(1).All(x=>string.IsNullOrEmpty(x)))
{
Debug.WriteLine(line);
}
Upvotes: 2