C# 如何返回排序后的数组而不编写故事(不变性介绍)?
我有一本字典,我把它投射到一个列表中,然后对它进行排序。之后,我返回结果。但是,我想知道是否有可能(如果有,如何)返回排序后的数组而不首先存储它C# 如何返回排序后的数组而不编写故事(不变性介绍)?,c#,linq,sorting,immutability,C#,Linq,Sorting,Immutability,我有一本字典,我把它投射到一个列表中,然后对它进行排序。之后,我返回结果。但是,我想知道是否有可能(如果有,如何)返回排序后的数组而不首先存储它 List<SomeType> thingies = dictionary.Select(element => element.Value).ToList(); thingies.Sort((the, thing) => the.Id.CompareTo(thing.Id)); return thingies; 你需要: ret
List<SomeType> thingies = dictionary.Select(element => element.Value).ToList();
thingies.Sort((the, thing) => the.Id.CompareTo(thing.Id));
return thingies;
你需要:
return dictionary.Select(element
=> element.Value.OrderBy(r=> r.Id).ToArray())
.ToList();
这将返回一个有序的值列表,而不修改原始的
数组
您正在寻找类似于returndictionary.Select(element=>element.Value.OrderBy(r=>r.Id.ToArray()).ToList()的内容代码注释>边注:考虑为“NAG,我不能把空类型作为列表类型”提供确切的消息。不是<代码>字典。选择(元素= >元素?值)< /C> >?你还可以解释“不存储”(假设不声明局部变量?)与“不可变”有关吗?@ Habib把它作为回复,这样我就可以接受答案。
return dictionary.Select(element
=> element.Value.OrderBy(r=> r.Id).ToArray())
.ToList();