0
currentUsers.GroupBy(user => user.ID)
            .Where(group => group.Count() > 1)
            .ToDictionary(group => group.Key, group => group.ToList()
            .AsEnumerable());

Tried to find duplicates by using GroupBy on the readonly collection but it throws null reference exception:

Object not set to an instance of the object

Tried converting the readonly collection to list , but it still throws the same exception.The linq query works fine in immediate window in Visual Studio 2017 but fails during runtime and debugging. Could someone please help?

  • What is `null` in this code, is it `currentUsers`, or anything thats inside any of the other statements? - Also see: https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it/4660186 – Caramiriel Jan 22 '20 at 14:13
  • Where does the data of _currentUsers_ come from? Maybe it's null – schlonzo Jan 22 '20 at 14:14

3 Answers3

0

currentUsers likely contains a null value.

Try:

currentUsers
        .Where(user => user != null)
        .GroupBy(user => user.ID)
        .Where(group => group.Count() > 1)
        .ToDictionary(group => group.Key, group => group.ToList()
        .AsEnumerable());

As a side note: if you're using a Dictionary<TKey, List<TValue>>, consider using ToLookup instead.

Rik
  • 26,673
  • 13
  • 47
  • 65
0

If currentUsers is not null, most probably it contains a null reference itself during runtime.

maxx313
  • 51
  • 4
0

Try this:

var result = currentUsers?.GroupBy(cu => cu?.ID)
                          .Select(g => new {g.Key, Count = g.Count()})
                          .Where(g => g.Count > 1)
                          .OrderByDescending(x => x.Count);

Then check if result is null

lior
  • 500
  • 2
  • 14