简体   繁体   中英

Restructuring data for sorting C#

I want to restructure my data from this question: Sorting elements inside a tuple by inner elements so that I can use LINQ to sort with the OrderBy operation. But the dictionary I have is transposed the wrong way.

  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);
        }

What is a good way to structure the data for sorting without losing the keys from the dictionary? One possibility I thought of for sorting without the dictionary is:

  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);
        }

You are missing the OOP Concept of Composition .

If you composite that key and Value to one object type you don't have to transpose it at all. You can use just a List instead of a Dictionary. The fact that you have to transpose gives a bad design smell.

GameType should be a property of the Game . Then you don't need two list. Just one List<Game> would be enough and then you have no problem of sorting the Games list by GameType .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM