如何对字典中的列表进行排序? C#
How can I Sort List in Dictionary? C#
我想根据数量 属性 对我的列表元素进行排序,并创建一个新的排序字典。 Lambda 表达式有可能吗?如果是,你能给我举个例子吗?
代码:
internal class Loss
{
string name;
double amount;
double cost;
public string Name { get => name; set => name = value; }
public double Amount { get => amount; set => amount = value; }
public double Cost { get => cost; set => cost = value; }
public Loss(string name, double amount, double cost)
{
Name = name;
Amount = amount;
Cost = cost;
}
}
internal class Program
{
static void Main(string[] args)
{
Dictionary<string, List<Loss>> unitLossDict = new Dictionary<string, List<Loss>>()
{
{ "Unit1",new List<Loss>() { new Loss("welding",1.2,500),
new Loss("drilling", 2.2, 500),
new Loss("housing", 0.2, 100) }},
{ "Unit2",new List<Loss>() { new Loss("welding",0.01,10),
new Loss("drilling", 3.2, 500),
new Loss("housing", 9.2, 800) }}
};
Dictionary<string, List<Loss>> sortedUnitLossDict = unitLossDict;
}
}
导入 System.Linq
并尝试下面的代码。
Dictionary<string, List<Loss>> SortedDictionary = new Dictionary<string, List<Loss>>();
foreach (var key in unitLossDict.Keys)
{
SortedDictionary.Add(key, unitLossDict[key].OrderBy(i => i.Amount).ToList());
}
我想根据数量 属性 对我的列表元素进行排序,并创建一个新的排序字典。 Lambda 表达式有可能吗?如果是,你能给我举个例子吗?
代码:
internal class Loss
{
string name;
double amount;
double cost;
public string Name { get => name; set => name = value; }
public double Amount { get => amount; set => amount = value; }
public double Cost { get => cost; set => cost = value; }
public Loss(string name, double amount, double cost)
{
Name = name;
Amount = amount;
Cost = cost;
}
}
internal class Program
{
static void Main(string[] args)
{
Dictionary<string, List<Loss>> unitLossDict = new Dictionary<string, List<Loss>>()
{
{ "Unit1",new List<Loss>() { new Loss("welding",1.2,500),
new Loss("drilling", 2.2, 500),
new Loss("housing", 0.2, 100) }},
{ "Unit2",new List<Loss>() { new Loss("welding",0.01,10),
new Loss("drilling", 3.2, 500),
new Loss("housing", 9.2, 800) }}
};
Dictionary<string, List<Loss>> sortedUnitLossDict = unitLossDict;
}
}
导入 System.Linq
并尝试下面的代码。
Dictionary<string, List<Loss>> SortedDictionary = new Dictionary<string, List<Loss>>();
foreach (var key in unitLossDict.Keys)
{
SortedDictionary.Add(key, unitLossDict[key].OrderBy(i => i.Amount).ToList());
}