leo*_*ora 0 c# linq collections
我有一个对象列表,我想按某个字段排序,然后找出"等级"或索引是某个名称.
例如,假设我有一个:
List<Location> Locations= new List<Location>();
Run Code Online (Sandbox Code Playgroud)
我想按人气排序
var list = this.Locations.OrderBy(r => r.PopularityPct);
Run Code Online (Sandbox Code Playgroud)
我现在想知道什么是"西班牙"的索引(注意:"西班牙"将是Name属性的查找,其中Name将是location对象的属性)现在该列表按流行度排序.
这样做最简单的方法是什么?
您可以轻松获取所有名称和索引,如下所示:
var list = this.Locations.OrderBy(r => r.PopularityPct)
.Select((value, index) => new { value, index });
Run Code Online (Sandbox Code Playgroud)
然后,例如:
var spainIndex = list.Single(x => x.value.Name == "Spain").index;
Run Code Online (Sandbox Code Playgroud)
或打印一切:
foreach (var pair in list)
{
Console.WriteLine("{0}: {1}", pair.index, pair.value.Name);
}
Run Code Online (Sandbox Code Playgroud)
这假设你想要排序后的排名.如果您想在初始列表中使用索引,则需要切换顺序:
var list = this.Locations.Select((value, index) => new { value, index });
.OrderBy(r => r.value.PopularityPct);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1241 次 |
| 最近记录: |