Search code examples
c#asp.net-coreienumerableasp.net-core-3.1

IEnumerable is not populating with expected data when using a ternary operator


I am using the following IEnumerable to create a EncounterEvents.

Everything is populating great except the last property which is called IsManaged.

It's a boolean, and I want it to be true if at least one of the EncounterTypeId values in the group is 99.

But even though I have verifed that at least one EncounterTypeId is 99, it's always false.

If I manually set it like IsManaged = true, then it's fine too.

Here is my code:

var encounterList = dungeonResults.GroupBy(x => new { x.GameType, x.GameId })
 .Select(group => new EncounterEvents
 {
     CharacterName = group.Select(g => g.GeneratedName).FirstOrDefault(),
     EncounterId = group.Select(g => g.ChapterId).FirstOrDefault().ToString(),
     EncounterName = String.Join("; ", group.Select(g => g.ChapterName).ToArray()),
     IsManaged = group.Select(g => g.EncounterTypeId).FirstOrDefault() == 99 ? true : false
 })
 .ToList();

Is there anything I need to do to get it to populate correctly?

Thanks!


Solution

  • The expression group.Select(g => g.EncounterTypeId).FirstOrDefault() is only evaluating the first record in the group, and it's probably not 99 in your case.

    You could better use group.Any(g => g.EncounterTypeId==99).

    to clarify, the final expression would be: IsManaged = group.Any(g => g.EncounterTypeId==99)

    it will assign true if any of the items in the collection being evaluated is true.