C# 排序具有多个对象的类型值的字典键

我用C#创建了一个词典,其中包含多个对象的类型值

...
Dictionary<string, object> phone = new Dictionary<string, object>();
Specifications n1;
n1.Price = 799;
n1.Weight = 600;
phone.Add("iphone8s",n1);

Specifications n2;
n2.Price = 499;
n2.Weight = 500;
phone.Add("huawei p40",n2);

Specifications n3;
n3.Price = 799;
n3.Weight = 500;
phone.Add("iphone13",n3);

...
public struct Specifications
{
    ...
    public int Price{ get; set; }
    public int Weight{ get; set; }
    ...

}

...

有没有一种方法可以按特定值对词典关键字进行排序。例如。
首先按升序对价格进行排序,如果价格相同,则按升序对重量进行两次排序。
结果是,字典里应该 先有华为P40,然后是iphone13,最后是iphone8s。

阅读 1.2k
1 个回答

Linq:

var results = phone
  .Select(e => new { Name: e.Key, Spec: e.Value })
  .OrderBy(e => e.Spec.Price)
  .ThenBy(e => e.Spec.Weight)
  .ToArray();

徒手写的,可能有误,看意思就好。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进