所以我有一个包含字符串键的Dictionary,值是一个对象列表。每个List中的每个对象都具有一个属性值,该值等于List的相关键。换句话说,Dictionary通过键按属性值对对象进行分组。例如,我们说有,
Dictionary<string, List<Animal>> GroupedByClass = new Dictionary<string, Animal>();
其中Animal是一个包含名为&#34; ClassType&#34;的字符串属性的对象。它有&#34; Mammal&#34;,&#34; Reptile&#34;或&#34; Amphibian&#34;等等的有效选项。
Animal类也可以有名为&#34; Species&#34;的字符串属性。它更独特地定义了词典中的每个对象。
字典内容的伪代码描述可以是:
<"Mammal", List<Animal>>
列表中的动物有物种&#34;狗&#34;,&#34; Cat&#34; &lt;&#34; Reptile&#34;,List&gt; 列表中的动物有Species&#34; Snake&#34;,&#34; Lizard&#34;和&#34; Turtle&#34; &lt;&#34;两栖动物&#34;,列表&gt; 列表中的动物有物种&#34; Salamander&#34;和&#34;青蛙&#34;
我想通过键值重新排列这个词典,使得键值为&#34; Reptile&#34;先是,然后是&#34;两栖动物&#34;,然后最后&#34;哺乳动物&#34;。请注意,我不想根据字母顺序对此进行排序,我想指定自己的订单。
我知道我可以通过简单地遍历字典几次来解决这个问题,只用正确的密钥提取项目。例如,我可以这样做,
Dictionary<string, List<Animal>> temp = new Dictionary<string, List<Animal>>();
foreach(KeyValuePair<string, List<Animal>> item in GroupedByClass)
{
if(item.Key == "Reptile")
{
temp.Add(item.Key, item.Value);
}
}
foreach(KeyValuePair<string, List<Animal>> item in GroupedByClass)
{
if(item.Key == "Amphibian")
{
temp.Add(item.Key, item.Value);
}
}
foreach(KeyValuePair<string, List<Animal>> item in GroupedByClass)
{
if(item.Key == "Mammal")
{
temp.Add(item.Key, item.Value);
}
}
return temp;
然而,这似乎不优雅,我想知道使用Linq查询和lambda表达式是否有更好的答案。
答案 0 :(得分:2)
这应该很接近(有一些语法错误):
var order = new [] {"Reptile","Amphibian","Mammal"};
var elems = dict.OrderBy(x=>order.IndexOf(x.Key));
如果要展平结果,则可以使用SelectMany:
var order = new [] {"Reptile","Amphibian","Mammal"};
var elems = dict.SelectMany(x=>x).OrderBy(x=>order.IndexOf(x.Species));
答案 1 :(得分:0)
Dictionary<string, List<Animal>> temp = new Dictionary<string,List<Animal>>();
(new List<string>() {"Reptile","Amphibian","Mammal"}).ForEach(x => temp.Add(x, GroupedByClass[x]));
答案 2 :(得分:0)
您可以定义一个枚举,并将其作为您的定义顺序。
enum Animal : int
{
Reptile = 0,
Amphibian = 1,
Mammal = 2
}
注意,因为你有简单的字符串,这是有效的,并且是直截了当的。但是,如果您最终得到具有空格的字符串,则可以使用枚举的DescriptionAttribute并在其与实际枚举之间进行操作。 Enumeration with Display String
通过对字符串使用枚举,您可以执行许多操作,但当然可以使用您所指定的整数进行排序。