Student Student - 1 year ago 63 Question

Can't Get IEnumerable of Inherited Class in LINQ Query

I am trying to convert some code from VB over to C# and have had an extremely hard time with this particular LINQ query. First I'll show the classes:

Public Class CompanyData
Property CompanyID As String = ""
Property VendorNumber As String = ""
Property VendorName As String = ""

End Class

Public Class MultiCompData
Inherits CompanyData

Property ExpCompanyId As String = ""
End Class

Then in the VB example what it does is Group all into MultiCompData in a multiCompGroup field, foreach through it and add to a different list of CompanyData if ExpCompanyId is null/empty. Code:

Sub ProcessMultiCompData(multiCompDataJEs As IEnumerable(Of MultiCompData), ByRef multiCompData As List(Of CompanyData), ByRef undeterminedDists As List(Of CompanyData))

Dim multiCompGroups =
From m In multiCompDataJEs
Group m By m.ExpCompanyId,
Into Group

For Each grp In multiCompGroups
If grp.ExpCompanyId = "" Then


In the foreach, grp has the following properties - ExpCompanyId, VendorNumber, VendorName and Group (which is the part I can't replicate in C#) Group being an IEnumerable. Is it not possible to add that IEnumerable in C# to multiCompGroups?? I have tried:

var multiCompGroups = from m in multiCompDataJEs group by new {m.ExpCompanyiD, m.VendorNumber, m.VendorName} into multiGroups

multiGroups doesn't show up as an IEnumerable in my grp value when I get to the foreach, i've also tried it this way:

var multiCompGroups = multiCompDataJEs.GroupBy(x => new {m.ExpCompanyId, m.VendorNumber, m.VendorName}).Select(y => new {y.Key.ExpCompanyId, y.Key.VendorNumber, y.Key.VendorName}).ToList();

Both are producing the same thing. I have the 3 properties show up when I do grp. but the "Into Group" (grp.Group in the VB code above) doesn't show up in C#. Is it even possible to do?

Answer Source

The C# you're looking for is:

var multiCompGroups =
    from m in multiCompDataJEs
    group m by new {m.ExpCompanyiD, m.VendorNumber, m.VendorName} into multiGroups
    select multiGroups;

foreach(var grp in multiCompGroups)
    if(grp.Key.ExpCompanyId == "")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download