【发布时间】:2019-07-06 16:32:35
【问题描述】:
我希望能够通过MyObj 中的任何属性来查询和排序Dictionary<int, MyObj>。
class MyObj
{
public string Symbol { get; set; }
public string Name { get; set; }
public int AtomicNumber { get; set; }
public int Id { get; set; }
public string toString()
{
return Symbol + " " + Name + " " + AtomicNumber + " " + Id;
}
}
class Program
{
private static void AddToDictionary(Dictionary<int, MyObj> elements,
string symbol, string name, int atomicNumber, int id)
{
MyObj theElement = new MyObj();
theElement.Symbol = symbol;
theElement.Name = name;
theElement.AtomicNumber = atomicNumber;
theElement.Id = id;
elements.Add(key: theElement.Id, value: theElement);
}
private static Dictionary<int, MyObj> BuildDictionary()
{
var elements = new Dictionary<int, MyObj>();
AddToDictionary(elements, "K", "Potassium", 19, 0);
AddToDictionary(elements, "Ca", "Calcium", 20, 1);
AddToDictionary(elements, "Sc", "Scandium", 21, 2);
AddToDictionary(elements, "Ti", "Titanium", 22, 3);
return elements;
}
static List<T> GetListOfProperty<T>(Dictionary<int, MyObj> colBlobs, string property)
{
Type t = typeof(MyObj);
PropertyInfo prop = t.GetProperty(property);
if (prop == null)
{
// throw new Exception(string.Format("Property {0} not found", f.Name.ToLower()));
Console.WriteLine(string.Format("Property {0} not found", property));
return new List<T>();
}
//still need to fix this
return colBlobs.Values
.Select(blob => (T)prop.GetValue(blob))
.OrderBy(x => x)
.ToList();
}
static SortedDictionary<int, MyObj> GetListOfProperty2<T>(Dictionary<int, MyObj> colBlobs, string property)
{
// CODE?
return sortedDict;
}
static void Main(string[] args)
{
Dictionary<int, MyObj> myColl = BuildDictionary();
var res = GetListOfProperty<string>(myColl, "Name");
foreach (var rr in res)
Console.WriteLine(rr.ToString());
//outputs : Which is only one property, the one selected
//--------
//Calcium
//Potassium
//Scandium
//Titanium
var res2 = GetListOfProperty2<string>(myColl, "Name");
//want to output the whole dictionary
//<1, {"Ca", "Calcium", 20,1}
//<0, {"K", "Potassium", 19, 0}
//<2, {"Sc", "Scandium", 21, 2}
//<3, {"Ti", "Titanium", 22, 3}
}
}
因为似乎不清楚我想要什么。我添加了示例输出。我很确定没有办法让这个问题更清楚。
【问题讨论】:
-
“失败”是什么意思?看起来该方法应该返回一个字典列表,但您试图只返回一个字典。我不明白您实际上要做什么。字典不是排序的集合。如果需要,请使用SortedDictionary。
-
这不行,因为“x”没有Key也没有Value。你的字典应该是什么样子的?你期望的键和期望值是多少?
-
我看不出 `.Select(blob => (T)prop.GetValue(blob))` 有什么用处,因为
blob的类型为KeyValue<int, MyObj>,但您正在尝试获取MyObj的属性... -
@unixsnob 您发布的代码在您声称它有效的情况下无法编译(“如果我返回列表它有效”)并按照@987654328 的预期抛出“对象与目标类型不匹配” @line 试图说服该代码至少运行时...
-
@HenrikHansen:嗨,我希望这足够清楚,您可以提交答案。我真的不明白为什么人们认为它如此不清楚。我只想通过对象内的属性来查询和排序字典。例如,为
MyObj的 AtomicNumber 属性 > 20 获取排序的对。