我想根據 Amount 屬性對我的 List 元素進行排序并創建一個新的排序字典。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;
}
}
uj5u.com熱心網友回復:
匯入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());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441050.html
上一篇:按重復元素對串列進行排序
