开发者

How to sort a List in C#?

I have the开发者_开发知识库 following List :

List<Dictionary<int, Dictionary<string, string>>> lngList
lngList.Add(new Dictionary<int,Dictionary<string,string>>().Add(1,new Dictionary<string,string>().Add("Item1Key","Item1Value")));
lngList.Add(new Dictionary<int,Dictionary<string,string>>().Add(3,new Dictionary<string,string>().Add("Item1Key","Item1Value")));
lngList.Add(new Dictionary<int,Dictionary<string,string>>().Add(2,new Dictionary<string,string>().Add("Item1Key","Item1Value")));
lngList.Add(new Dictionary<int,Dictionary<string,string>>().Add(4,new Dictionary<string,string>().Add("Item1Key","Item1Value")));

I need to sort (ascending) this list on the basis of the integer value present inside the Dictionary.

This has to be achieved without using LINQ.

P.S. This is assuming all the the integer values added are unique.


If each dictionary has only one key, and you don’t care what happens if it has multiple, you can do this:

lngList.Sort((a, b) => a.Keys.First().CompareTo(b.Keys.First()));

Since you stated that “This has to be achieved without using LINQ”, I assume you mean that the System.Linq namespace is not available to you. But that’s not a problem: you only need .First(), which you can easily define yourself:

public static class EnumerableExtensions {
    public static T First<T>(this IEnumerable<T> source) {
        using (var e = source.GetEnumerator()) {
            if (!e.MoveNext())
                throw new InvalidOperationException("The collection is empty.");
            return e.Current;
        }
    }
}

If you have to use .NET 2.0, which doesn’t have lambda expressions or extension methods, use this instead:

lngList.Sort(new Comparison<Dictionary<int, Dictionary<string, string>>>(sortFunc));

public int sortFunc(Dictionary<int, Dictionary<string, string>> a,
                    Dictionary<int, Dictionary<string, string>> b)
{
    return First(a.Keys).CompareTo(First(b.Keys));
}

public static T First<T>(IEnumerable<T> source) {
    using (var e = source.GetEnumerator()) {
        if (!e.MoveNext())
            throw new InvalidOperationException("The collection is empty.");
        return e.Current;
    }
}


The easiest way to solve your solution is to use a SortedList instead of a List:

example:

SortedList<int, Dictionary<string, string>> lngList;

this will be sorted by default on the integer value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜