Skip to main content
 首页 » 编程设计

c#之按字母顺序排序的最有效方法是什么

2024年02月23日15webabcd

我有这样的类结构:

List<myObject> myList = new List<myObject>(); 
 
myObject 
{ 
    List<myOtherObject> myOtherList = new List<myOtherObject>(); 
} 
 
myOtherObject 
{ 
    string name; 
} 

按字母顺序打印 myList 中所有 names 的最佳方法是什么?

我可以这样做,但我怀疑有更有效的方法来实现同样的目的:

foreach(myObject a in myList) 
{ 
    foreach(myOtherObject b in a.myOtherList) 
    { 
         newList.Add(b.name); 
    } 
} 
 
//print newList alphabetically 

编辑:

我能够更改结构,现在我只需要根据 name 属性对 myOtherList 进行排序。

我试过这样做,但似乎无法排序:

myOtherList.OrderBy(obj=>obj.name); 

它是就地排序,还是我需要将它分配给另一个列表?

请您参考如下方法:

使用 linq(方法符号):

foreach (var result in myList 
    .SelectMany(l => l.myOtherList) 
    .OrderBy(obj => obj.Name)) 
{ 
    Console.WriteLine(result.name); 
} 

这会将 myOtherList 的 myList 扁平化为 myOtherObject 的扁平列表。