简体   繁体   English

如何在具有嵌入式列表的列表上使用Linq Orderby

[英]How to use Linq orderby on list with embedded list

My list contains addresses and I want to order the list accordingly. 我的列表包含地址,我想相应地订购该列表。 The problem I have is that in the list is a list item for street lines which permits zero or more street address lines. 我的问题是列表中是街道线的列表项,允许零个或多个街道地址线。 I can easily sequence all the other elements with this command: 我可以使用此命令轻松地对所有其他元素进行排序:

**C#**
Sites == Sites.OrderBy(x => x.SiteName).ThenBy(x => x.State).ThenBy(x => x.City).ThenBy(x => x.Zip).ToList

**VB.NET**
Sites = Sites.OrderBy(Function(x) x.SiteName).ThenBy(Function(x) x.State).ThenBy(Function(x) x.City).ThenBy(Function(x) x.Zip).ToList

Most addresses contain one value in the StreetLines list but not all. 大多数地址在StreetLines列表中包含一个值,但不是全部。 The compiler allows me to add another thenby argument for Streetlines but I'm not sure what it will do. 编译器允许我为Streetlines添加另一个thenby参数,但是我不确定它会做什么。 Suppose that there are multiple addresses with the values shown here: 假设有多个地址,其值如下所示:

1.  Streetline.Count = 0       
2.  Streetline.Count = 2 (0) = "1234 Main St."  (1) = "6th Floor"
3.  Streetline.Count = 1 (0) = "P.O. Box 9999"
4.  Streetline.Count = 2 (0) = "1234 Main St."  (1) = "4th Floor"
5.  Streetline.Count = 1 (0) = "101 Pacific Blvd."

Will reordering occur or will I get a runtime error? 重新排序会发生还是会出现运行时错误? What will the sequence of the addresses be assuming that all the other single value fields are identical? 假设所有其他单个值字段都相同,那么地址的顺序将是什么?

.OrderBy() needs to generate one single rank-able value (something which is IComparable for ordering) per element. .OrderBy()需要为每个元素生成一个单一的可排序值(可以通过IComparable排序)。

So if your element has a list of strings (streetlines) - you need to write a function that will generate a value / ranking string per set of streetlines. 因此,如果您的元素具有字符串(街道线)列表-您需要编写一个函数,该函数将为每条街道线生成一个值/排名字符串。

Trivial example: Sites.OrderBy(x => x.StreetLines?.FirstOrDefault()); 一个简单的例子:Sites.OrderBy(x => x.StreetLines?.FirstOrDefault()); //picking the first available streetline //选择第一个可用的街道

The .ThenBy() is only a secondary group sort (example if two sites had the same PO Box), and works on the same basis (single rank-able value per element). .ThenBy()仅是次要的组排序(例如,如果两个站点具有相同的邮政信箱),并且在相同的基础上工作(每个元素具有单个可排序的值)。

The main thing is to figure out your data and the actual ranking scheme you want to implement. 最主要的是弄清楚您的数据和要实施的实际排名方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM