Search code examples
c#linq

Error CS0029: Cannot implicitly convert type 'type' to 'type' in C# LINQ


I encountered error CS0029 in LINQ code. The code is not mine, but I have to deal with this code. The complete error message is Error CS0029: Cannot implicitly convert type System.Collections.Generic.IEnumerable<AnonymousType#1> to System.Collections.Generic.IEnumerable<AnonymousType#2>

in code fragment

 grouped =
  from r in result
  group r by new
  {
   r.KindOfCalculationsNumber,
   r.KindOfCalculationsCode,
   r.PeriodFor,
   r.SnuType,
   r.SnuName,
   r.IsAssist,
   r.DDS,
   r.DDP,
   r.PRC,
   r.KFTType,
   r.WRK,
   r.NUMERATOR,
   r.DENOMINATOR,
   r.FOVTYPE,
   r.RATEVALUE,
   r.INDFCT,
   r.KFTKV,
   r.OsnNote,
   r.TransferDate,
   r.ExcludeFromItog,
   r.ExcludeFromItogInter,
   r.SnuTypeCode,
   r.TransferType
  }
   into g
   let k = g.Key
   orderby k.SnuTypeCode, k.KindOfCalculationsNumber, k.PeriodFor, g.Min(t => t.SnuNumber)
   select new
   {
    k.KindOfCalculationsNumber,
    k.KindOfCalculationsCode,
    k.PeriodFor,
    k.SnuType,
    k.SnuTypeCode,
    SnuNumber = g.Min(t => t.SnuNumber),
    k.SnuName,
    k.IsAssist,
    k.DDS,
    k.DDP,
    k.PRC,
    k.KFTType,
    k.WRK,
    k.NUMERATOR,
    k.DENOMINATOR,
    k.FOVTYPE,
    k.RATEVALUE,
    k.INDFCT,
    k.KFTKV,
    k.OsnNote,
    TaxDeduction = g.Sum(t => t.TaxDeduction),
    TransferSum = g.Sum(t => t.TransferSum),
    k.TransferDate,
    k.ExcludeFromItog,
    k.ExcludeFromItogInter,
    Sum = g.Sum(t => t.Sum)
   };

The error points at line select new. Can anyone advise me what is wrong in this code? Something for me to begin with. Full CS file that is being compiled can be downloaded from https://disk.yandex.ru/d/S3AGUWMciF_HFQ


Solution

  • You are using different data sets (in your case anonymous types) and trying to assign them to the same variable grouped.

    You will therefore need to either change how you retrieve the data such that it is the same type, or you can simply declare a new variable to store the data.

    Currently your simplified use case is as below:

    var grouped = new { someValue = 1 };
    grouped = new { someValue = 1, anotherValue = 2 }; // fails: Cannot implicitly convert type 'AnonymousType#1' to 'AnonymousType#2'
    

    You can resolve that as follows:

    var grouped = new { someValue = 1 };
    var grouped2 = new { someValue = 1, anotherValue = 2 }; // new variable for new data type
    grouped = new { someValue = 5 }; // Note that this works because it is the same type as the original value of grouped