重组数据以排序C#

时间:2015-07-31 02:59:59

标签: c# linq sorting dictionary

我想重构这个问题的数据:Sorting elements inside a tuple by inner elements以便我可以使用LINQ对OrderBy操作进行排序。但是我所拥有的字典却以错误的方式转换。

  public class Gamedat
    {
        public string[] Games { get; set; }

        public string[] Gtypes { get; set; }

        public Dictionary<string, int[]> Playdata { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Gamedat dataframe = new Gamedat();
            dataframe.Games = new string[] { "Game 1", "Game 2", "Game 3", "Game 4", "Game 5" };
            dataframe.Gtypes = new string[] { "A", "B", "C", "B", "A" };
            dataframe.Playdata = new Dictionary<string, int[]>();

            //Add dictionary items
            int[] a = { 1, 0, 3, 4, 0 };
            int[] b = { 3, 0, 9, 10, 0 };
            int[] c = { 2, 3, 3, 5, 0 };

            dataframe.Playdata.Add("Jack", a);
            dataframe.Playdata.Add("Jane", b);
            dataframe.Playdata.Add("James", c);
        }

在不丢失字典中的键的情况下,为排序构建数据的好方法是什么?我想到的没有字典排序的一种可能性是:

  public class Gamedat
    {
        public string Games { get; set; }

        public string Gtypes { get; set; }   
    }

    class Program
    {
        static void Main(string[] args)
        {
        List<Gamedat> dataframe = new List<Gamedat> {new Gamedat { Game = "Game 1", Gtypes = "A"},
        new Gamedat { Game = "Game 2", Gtypes = "B"},
        new Gamedat { Game = "Game 3", Gtypes = "C"},
        new Gamedat { Game = "Game 4", Gtypes = "B"},
        new Gamedat { Game = "Game 5", Gtypes = "A"},
        };


            var result = dataframe.OrderBy(x => x.Gtypes);
        }

1 个答案:

答案 0 :(得分:3)

您错过了Composition的OOP概念。

如果将该键和值合成为一种对象类型,则根本不需要对其进行转置。您只能使用List而不是Dictionary。你必须转置的事实会给人一种糟糕的设计气味。

GameType应该是Game的属性。那你就不需要两个清单了。只需一个List<Game>即可,然后您就可以按GamesGameType列表进行排序。