I have the following scenario when grouping a collection:
var result = data.GroupBy(x => x.Name.Split(new char[] { '-' })[1].Trim());
where data variable is of type ObservableCollection<Data>
When I check for
if(result.Count()>0)
it throws an IndexOutOfRangeException
of course this happens because the string split operation throws an exception.
The question is: is there a way to check if the result of the grouping is not null and avoiding the exception?
First of all, Enumerable.Count
just executes the deferred executed LINQ query(GroupBy
uses deferred execution, look at the remarks section). So Count
isn't to blame here.
You are splitting by -
and accessing this array at index 1 which is the second item. Obviously there is no second item because there was no -
. So it has nothing to do with null
.
Maybe it is sufficient to take only those where there is a second token:
var result = data
.Select(x => new{ Data = x, Split = x.Name.Split(new char[] { '-' }) })
.Where(x => x.Split.Length >= 2)
.GroupBy(x => x.Split[1].Trim());
or the second if there is a second, otherwise the first:
var result = data
.Select(x => new{ Data = x, Split = x.Name.Split(new char[] { '-' }) })
.GroupBy(x => x.Split.Length >= 2 ? x.Split[1].Trim() : x.Split[0].Trim());
You can do the following:
var result = data.GroupBy(x => x.Name.Contains('-') ? x.Name.Split('-')[1].Trim() : "");
If you don't like the ?: operator or want it less compact, use:
var result = data.GroupBy(x =>
{
string name = x.Name;
if (name.Contains('-')) return name.Split('-')[1].Trim();
return "";
});
Note: I used Split('-')
instead of Split(new char[] { '-' })
This is probably more intuitive than the solution of Tim Schmelter, but use what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With