Dictionary 按 Value 的某字段属性排序


namespace Microshaoft
{
    using System;
    using System.Linq;
    public class Class1
    {
        static void Main(string[] args)
        {
            var entrys = new[]
                            {
                                new
                                    {
                                        Name = "Alice"
                                        , Score = 5
                                    },
                                new
                                    {
                                        Name = "Bob"
                                        , Score = 40
                                    },
                                new
                                    {
                                        Name = "Bob"
                                        , Score = 50
                                    }
                            };
            Console.WriteLine("原始数据");
            var dictionary = entrys.ToDictionary
                                        (
                                            entry => Guid.NewGuid() //entry.Name
                                        );
            dictionary.ToList().ForEach
                                    (
                                        entry =>
                                        {
                                            Console.WriteLine("Key: {0}, Value: Name: {1}, Score: {2}, ", entry.Key, entry.Value.Name, entry.Value.Score);
                                        }
                                    );
            Console.WriteLine("OrderBy方法按单字段排序");
            var result = dictionary.OrderByDescending
                                        (
                                            entry => entry.Value.Score
                                        );
            result.ToList().ForEach
                                (
                                    entry =>
                                    {
                                        Console.WriteLine("Key: {0}, Value: Name: {1}, Score: {2}, ", entry.Key, entry.Value.Name, entry.Value.Score);
                                    }
                                );
            Console.WriteLine("Linq 查询按多字段排序");
            result =
                        from pair in dictionary
                        orderby pair.Value.Name, pair.Value.Score descending
                        select pair;
            result.ToList().ForEach
                                (
                                    entry =>
                                    {
                                        Console.WriteLine("Key: {0}, Value: Name: {1}, Score: {2}, ", entry.Key, entry.Value.Name, entry.Value.Score);
                                    }
                                );
            Console.ReadLine();
        }
    }
}

posted @ 2012-04-06 01:41  于斯人也  阅读(618)  评论(0编辑  收藏  举报