C# 如何按实体依赖项对字典排序
我有一本字典。它包含类型和字符串:C# 如何按实体依赖项对字典排序,c#,sorting,dictionary,C#,Sorting,Dictionary,我有一本字典。它包含类型和字符串: var myDictionary = new Dictionary<Type, string>(); myDictionary.Add(typeof(Person), "Person"); myDictionary.Add(typeof(IPerson), "IPerson"); myDictionary.Add(typeof(IGoodStudent), "IGoodStudent");
var myDictionary = new Dictionary<Type, string>();
myDictionary.Add(typeof(Person), "Person");
myDictionary.Add(typeof(IPerson), "IPerson");
myDictionary.Add(typeof(IGoodStudent), "IGoodStudent");
myDictionary.Add(typeof(IStudent), "IStudent");
myDictionary.Add(typeof(GoodStudent), "GoodStudent");
myDictionary.Add(typeof(Student), "Student");
如何对字典进行排序?您可以创建一个已排序的字典并使用自定义的IComparer:
SortedDictionary<Type, string> myDictionary= new SortedDictionary<Type, string>(new SortedTypeComparer());
myDictionary.Add(typeof(Person), "Person");
// Etc....
SortedDictionary myDictionary=new SortedDictionary(new SortedTypeComparer());
myDictionary.Add(typeof(Person),“Person”);
//等等。。。。
使用这样的自定义IComparer:
public class SortedTypeComparer : IComparer<Type>
{
public int Compare(Type x, Type y)
{
// Logic here to compare the types however you wish
// - If less than 0, x is less than y.
// - If 0, x equals y.
// - If greater than 0, x is greater than y
}
}
公共类分类类型比较器:IComparer
{
公共整数比较(类型x、类型y)
{
//此处的逻辑用于比较您希望的类型
//-如果小于0,则x小于y。
//-如果0,x等于y。
//-如果大于0,则x大于y
}
}
您可以创建已排序的词典并使用自定义的IComparer:
SortedDictionary<Type, string> myDictionary= new SortedDictionary<Type, string>(new SortedTypeComparer());
myDictionary.Add(typeof(Person), "Person");
// Etc....
SortedDictionary myDictionary=new SortedDictionary(new SortedTypeComparer());
myDictionary.Add(typeof(Person),“Person”);
//等等。。。。
使用这样的自定义IComparer:
public class SortedTypeComparer : IComparer<Type>
{
public int Compare(Type x, Type y)
{
// Logic here to compare the types however you wish
// - If less than 0, x is less than y.
// - If 0, x equals y.
// - If greater than 0, x is greater than y
}
}
公共类分类类型比较器:IComparer
{
公共整数比较(类型x、类型y)
{
//此处的逻辑用于比较您希望的类型
//-如果小于0,则x小于y。
//-如果0,x等于y。
//-如果大于0,则x大于y
}
}
“我如何对字典排序?”一点也不,除非您使用SortedDictionary
。字典
从不保证任何顺序。为什么人
在学生
之前IStudent
继承了IPerson
其中Person
实现了它,所以根据您的描述,我假设他们的顺序是相反的?那么它不应该是IPerson,IStudent,IGoodStudent,Person,Student,GoodStudent
?@Knoop“IStudent继承了IPerson”是正确的吗?我认为,“IStudent implements IPerson”是最适合这种情况的case@DIlshodK一个接口
按其本身的定义不能实现任何东西。所以不,我想说,IStudent实现IPerson
不是它的工作方式,既不是IStudent
也不是IPerson
实现任何东西。“我如何对我的字典排序?”一点也不是,除非你使用SortedDictionary
。字典
从不保证任何顺序。为什么人
在学生
之前IStudent
继承了IPerson
其中Person
实现了它,所以根据您的描述,我假设他们的顺序是相反的?那么它不应该是IPerson,IStudent,IGoodStudent,Person,Student,GoodStudent
?@Knoop“IStudent继承了IPerson”是正确的吗?我认为,“IStudent implements IPerson”是最适合这种情况的case@DIlshodK一个接口
按其本身的定义不能实现任何东西。所以不,我想说,IStudent实现IPerson
不是它的工作方式,既不是IStudent
也不是IPerson
实现任何东西。