Search code examples
c#linqgroup-byanonymous-types

How to define the type of a grouping by 2 keys


I have the following property:

public List<IGrouping<????, License>> LicensesInfo
{
   get;
   set;
}

Which I want to assign values from here:

var groupedLicenses = licenses.GroupBy(x => new {x.Id, x.Name}).ToList();

The error says:

Cannot implicitly convert type 'System.Collections.Generic.List<System.Linq.IGrouping<<anonymous type: string Id, string Name>, License>>' to 'System.Collections.Generic.List<System.Linq.IGrouping<????, License>>'

I've tried variations of {string, string} in order to define that anonymous type, without luck.

I also tried creating an object and used it in the GroupBy like this: .GroupBy(x => new AccountInfo(x.Id, x.Name)) but they do not even get grouped if used like that.


Solution

  • Try making your AccountInfo class implement IEquatable.

    public class AccountInfo : IEquatable<AccountInfo>
    {
        public int Id;
        public string Name;
    
        public bool Equals(AccountInfo other)
        {
            return other != null && Id == other.Id && Name == other.Name;
        }
    
        public override int GetHashCode()
        {
            return HashCode.Combine(Id, Name);
        }
    }
    

    or if you are using C# 9.0 you can use record.

    public record AccountInfo 
    {
        public int Id;
        public string Name;
    
    }