[英]How to sort a dictionary in the same order of another dictionary in c#
我有两本字典,其中一部由:
1) <Id, Name>
该词典按“名称”排序
另一本字典,由:
2) <Id, ListOfValues>
这本字典未排序。
我必须按照与第一个字典相同的顺序对第二个字典进行排序,我可以使用Id作为公共点,我该怎么做?
我如何排序第二本字典
String json = data as string;
var rawData = JsonConvert.DeserializeObject<List<SectionItem>>(json);
/* New dictionary used to order item for name */
Dictionary<string, string> dataToOrder = new Dictionary<string, string>();
var name ="";
/* Getting data in "local language" */
var local_lang = ConfigurationContext.CurrentLocale;
/* In dataToOrder I insert name and Id*/
foreach (SectionItem si in rawData)
{
name = si.Entities[local_lang].Name;
dataToOrder.Add(name, si.Id);
}
/* List with ordered data by name*/
var orderedData = dataToOrder.OrderBy(kvp => kvp.Key).ToList();
现在,我必须按orderedData的相同顺序对原始数据的每个元素进行排序,我该怎么做呢?
public class SectionItem
{
public string Id;
public Dictionary<string, EntityGroup> Entities;
}
假设你要排序SecondDictionary
根据重点 dataToOrder
,你可以做到这一点。
在第一个字典中查找seconddiction Key
的索引,并用于订购字典。
var ids = dataToOrder.Keys.ToList();
SecondDictionary.OrderBy(x=> ids.Contain(x.Key)? ids.IndexOf(x.Key) : int.MaxValue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.