c#如何按值列对排序列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1250281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# How to sort a sorted list by its value column
提问by Grant
i have a generic sorted list "results" with key = some filename and value = boolean.
我有一个通用的排序列表“结果”,键 = 某个文件名,值 = 布尔值。
I would like to sort the list by the boolean entry or value column. does anyone know how i can do this?
我想按布尔条目或值列对列表进行排序。有谁知道我该怎么做?
Thanks!
谢谢!
采纳答案by spender
SortedList is optimized so that inertions occur in an ordered fashion, such that enumeration occurs in a sorted order at minimal cost. Anything else requires a re-sort. Thus:
SortedList 进行了优化,以便以有序的方式进行插入,从而以最小的成本以有序的顺序进行枚举。其他任何事情都需要重新排序。因此:
SortedList<string,bool> l=new SortedList<string, bool>();
l.Add("a",true);
l.Add("a",false);
l.Add("b",true);
l.Add("b",false);
var orderByVal=l.OrderBy(kvp => kvp.Value);
but this enumeration will be significantly slower to calculate, and be performed up-front, requiring extra storage to do so.
但是这种枚举的计算速度要慢得多,并且需要预先执行,因此需要额外的存储空间。
Depending on your situation it might be cheaper to maintain 2 SortedList instances with the key/value reversed.
根据您的情况,维护 2 个 SortedList 实例并反转键/值可能会更便宜。
回答by C-Pound Guru
In .NET 2.0, you could add your items to a SortedList:
在 .NET 2.0 中,您可以将项目添加到 SortedList:
public static List<MyObject> SortedObjects(IEnumerable<MyObject> myList) {
SortedList<string, MyObject> sortedList = new SortedList<string, MyObject>();
foreach (MyObject object in myList) {
sortedList.Add(object.ValueIWantToSort, object);
}
return new List<MyObject>(sortedList.Values);
}
回答by mansoor
For descending all list items
用于降序所有列表项
list.OrderByDescending();
or
或者
var list = list.OrderByDescending(x => x.Product.Name)
.ThenBy(x => x.Product.Price).ToList();
回答by David Fawzy
Normally that sorted by the first key on the list so if you swap the key and value on the add, then match that on the binding that sample example i use and work fine
通常按列表中的第一个键排序,因此如果您在添加时交换键和值,然后在我使用的示例示例的绑定上匹配它并且工作正常
public static SortedList<string, string> GetCountries(string conn)
{
var dict = new SortedList<string, string>();
dict.Add("","Select One");
var sql = "SELECT [CountryID] ,[Descr] FROM [dbo].[Countries] Order By CountryID ";
using (var rd = GetDataReader(conn, sql))
{
while (rd.Read())
{
dict.Add(rd["Descr"].ToString(), rd["CountryID"].ToString());
}
}
return dict;
}
Dim List As SortedList(Of String, String) = VDB.CoreLib.DbUtils.GetCountries(connDB)
ddlBankCountry.DataSource = List
ddlBankCountry.DataTextField = "Key"
ddlBankCountry.DataValueField = "Value"
ddlBankCountry.DataBind()