如何使用 LINQ 对 IEnumerable或对两个数据表联接进行排序

本文关键字:排序 两个 数据表 AnonymousType LINQ 何使用 IEnumerable | 更新日期: 2023-09-27 18:36:08

我正在连接两个数据表并使用 LINQ 进行选择。我在"排序"行中收到错误。"'接触'这个名字在当前语境中并不存在"。如果我按"客户"变量中的列排序,它可以工作,但不使用"联系人"变量中的列。

然后我删除了 orderby 行并尝试使用 lambda 表达式对其进行排序,如下所示:

orders.OrderBy(o => (string) o["ContactName"]; 

并且我收到一个错误"无法将 [] 的索引应用于类型为'匿名类型#1'的表达式。我不想仅仅为了排序而创建一个新类。

任何想法如何进行这种排序。我将使用两个表中的多个列进行排序。

法典:

  var orders = (from customer in Customers.AsEnumerable()
                          join contact in Contacts.AsEnumerable()
                              on (int) customer["CustomerID"] equals (int) contact["CustomerID"] into outer
                                from contact in outer.DefaultIfEmpty()
                                orderby contact["ContactName"]   
                          select new
                                     {
                                         ContactID = (int) contact["ContactID"]),
                                         Name =  (string) contact["ContactName"]),
                                         City =  (string) contact["City"])
                                  });

如何使用 LINQ 对 IEnumerable<AnonymousType 进行排序>或对两个数据表联接进行排序

存在一些语法问题(偏执太多,例如 contact["ContactID"]) ),这应该有效:

var orders =  from customer in Customers.AsEnumerable()
              join contact in Contacts.AsEnumerable()
              on customer.Field<int>("CustomerID") equals contact.Field<int>("CustomerID") into outer
                  from contact in outer.DefaultIfEmpty()
                  orderby contact["ContactName"]   
                  select new
                  {
                        ContactID = contact.Field<int>("ContactID"),
                        Name =  contact.Field<String>("ContactName"),
                        City =  contact.Field<String>("City")
                  };

旁注:我会使用强类型Field扩展方法。