Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# IEnumerable.Count() throws IndexOutOfRangeException

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?

like image 537
Mina Wissa Avatar asked Oct 21 '15 13:10

Mina Wissa


2 Answers

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());
like image 189
Tim Schmelter Avatar answered Oct 26 '22 08:10

Tim Schmelter


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.

like image 29
Andy Avatar answered Oct 26 '22 09:10

Andy