0

I am trying to convert the following LINQ code from VB.NET to C#, which is performed on the DataTable "tvp_dtl". Followed by VB code.

Dim query
query = From row In tvp_dtl
        Group row By dataGroup = New With {
            Key .Tmall_txn_no = row.Field(Of String)("Tmall_txn_no"),
            Key .stock_code = row.Field(Of String)("stock_code"),
            Key .ItemNameLocalLang = row.Field(Of String)("ItemNameLocalLang"),
            Key .ItemUnitPrice = row.Field(Of String)("ItemUnitPrice"),
            Key .itemTotalAmount = row.Field(Of String)("itemTotalAmount")
        } Into Group
        Select New With {
            .Tmall_txn_no = dataGroup.Tmall_txn_no,
            .stock_code = dataGroup.stock_code,
            .ItemNameLocalLang = dataGroup.ItemNameLocalLang,
            .ItemUnitPrice = dataGroup.ItemUnitPrice,
            .itemTotalAmount = dataGroup.itemTotalAmount,
            .SumAmount = Group.Sum(Function(x) Integer.Parse(x.Field(Of String)("ItemNumber")))}

Here is the version I wrote in C#

var query = from row in tvp_dtl
        group row by new
        {
            row.Tmall_txn_no = row.Field<string>("Tmall_txn_no"),
            row.stock_code = row.Field<string>("stock_code"),
            row.ItemNameLocalLang = row.Field<string>("ItemNameLocalLang")
        } into dataGroup
        select new
        {
            Tmall_txn_no = dataGroup.Field<string>("Tmall_txn_no"),
            stock_code = dataGroup.Field<string>("stock_code"),
            ItemNameLocalLang = dataGroup.Field<string>("ItemNameLocalLang"),
            ItemUnitPrice = dataGroup.Field<string>("ItemUnitPrice"),
            itemTotalAmount = dataGroup.Field<string>("itemTotalAmount"),
            SumAmount = dataGroup.Sum(x => int.Parse(x.Field<string>("ItemNumber") * int.Parse(x.Field<string>("QtyPerSet"))))
        };

But I think it is incorrect. Besides I got this error when using "tvp_dtl"

Could not find the implementation of the query pattern for source type "DataTable". Group By not found

Alfredlau
  • 35
  • 1
  • 7

1 Answers1

1

DataTable isn't an IEnumerable and even worse it doesn't provide the method required by the compiler to behave as an enumerable.

public class DataTable : MarshalByValueComponent, IListSource, ISupportInitializeNotification, ISupportInitialize, ISerializable, IXmlSerializable

Luckily there's an extension method that fixes that.

Try this:

var query =
    from row in tvp_dtl.AsEnumerable()
Enigmativity
  • 113,464
  • 11
  • 89
  • 172