IEnumerable <t>使用匿名方法</t>

时间:2011-04-23 12:17:44

标签: c# .net linq

我不知道如何摆脱这个错误?

错误1使用泛型类型'System.Collections.Generic.IEnumerable'需要1个类型参数C:\ Users \ huzaifa.gain \ documents \ visual studio 2010 \ Projects \ VendInvoiceImport \ VendInvoiceImport \ Program.cs 34 24 VendInvoiceImport < / p>

private static IEnumerable<string , string >  DistinctInvoiceNumber(DataTable   VendorInvoiceStagingTable)
       {
           var InvoiceLinecollection = VendorInvoiceStagingTable.AsEnumerable().Select(t => new {  number = t.Field<string>(VendInvoice.Number),LineNumber = t.Field<string>(VendInvoice.LineNumber)}).Distinct();
        return InvoiceLinecollection;
      }

enter image description here

2 个答案:

答案 0 :(得分:4)

您的Linq查询返回匿名类型的序列,但方法不能返回匿名类型。您有几种选择:

  • 返回IEnumerable<Tuple<string, string>>

    private static IEnumerable<Tuple<string, string>>  DistinctInvoiceNumber(DataTable   VendorInvoiceStagingTable)
    {
        var InvoiceLinecollection = VendorInvoiceStagingTable
                                        .AsEnumerable()
                                        .Select(t => Tuple.Create(t.Field<string>(VendInvoice.Number), t.Field<string>(VendInvoice.LineNumber)))
                                         .Distinct();
        return InvoiceLinecollection;
    }
    
  • 按照另一个答案中的建议返回IDictionary<string, string>(假设您的查询未返回重复的密钥)

    private static IDictionary<string, string> DistinctInvoiceNumber(DataTable   VendorInvoiceStagingTable)
    {
        var InvoiceLinecollection = VendorInvoiceStagingTable
                                        .AsEnumerable()
                                        .Select(t => Tuple.Create(t.Field<string>(VendInvoice.Number), t.Field<string>(VendInvoice.LineNumber)))
                                        .Distinct()
                                        .ToDictionary(t => t.Item1, t => t.Item2);
        return InvoiceLinecollection;
    }
    
  • 为此创建一个具有2个字符串属性的类,并返回该类的序列

    private static IEnumerable<InvoiceLine>  DistinctInvoiceNumber(DataTable   VendorInvoiceStagingTable)
    {
        var InvoiceLinecollection = VendorInvoiceStagingTable
                                        .AsEnumerable()
                                        .Select(t => new InvoiceLine(t.Field<string>(VendInvoice.Number), t.Field<string>(VendInvoice.LineNumber)))
                                        .Distinct();
        return InvoiceLinecollection;
    }
    

答案 1 :(得分:1)

为什么不使用Dictionary<string, string>

private static Dictionary<string , string >  DistinctInvoiceNumber(DataTable   VendorInvoiceStagingTable)
       {
           var InvoiceLinecollection = VendorInvoiceStagingTable.AsEnumerable().Select(t => new {  number = t.Field<string>(VendInvoice.Number),LineNumber = 
                 t.Field<string>(VendInvoice.LineNumber)}).ToDictionary();
            return InvoiceLinecollection;
          }