简体   繁体   中英

C# Linq data structure, for eventual data binding. Best way to do?

I have a set of "parts". Each part has a name and set of attributes. An attribute is a set of string keys and values. For example:

Part 1
    Width   200
    Depth   400
    Voltage 240V

I'm storing the parts and their attributes in a dictionary like this:

Dictionary<string, Dictionary<string, string>> parts;

So I can see if a part exists with parts.ContainsKey(part) and if it does, I can then see if an attribute exists with parts[part].ContainsKey(attribute). So far, so banal.

Now what I want to do is either data bind this structure, or otherwise generate a set of rows, where each column is an attribute. Not all parts have all attributes, so there will be "nulls" in places. I have access to a list of all attributes found in the entire set, as List (there are 59 possible attributes in the actual production system).

My code for generating a set of rows, assuming the first column is the part name, is the rather clunky code below. It results in a List of Lists of string. One List of String for each part (one "row" for each part).

I'm pretty sure there's a simple one liner Linq statement for this. I'm hoping I can use it to data-bind to a list or data grid to display it at some point. Can anyone help me out with it?

I provide a full repro below (add a new C# console project), with some example data.

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {              
            // The set of parts.

            Dictionary<string, Dictionary<string, string>> hashPartToAttributes = new Dictionary<string,Dictionary<string,string>>();

            hashPartToAttributes.Add("Part 1", new Dictionary<string,string>());
            hashPartToAttributes.Add("Part 2", new Dictionary<string,string>());
            hashPartToAttributes.Add("Part 3", new Dictionary<string,string>());
            hashPartToAttributes.Add("Part 4", new Dictionary<string,string>());

            // Add in all attributes for all of the parts.

            {
                hashPartToAttributes["Part 1"].Add("Width", "200");
                hashPartToAttributes["Part 1"].Add("Height", "400");
                hashPartToAttributes["Part 1"].Add("Depth", "600");

                hashPartToAttributes["Part 2"].Add("Width", "300");
                hashPartToAttributes["Part 2"].Add("Height", "700");
                hashPartToAttributes["Part 2"].Add("Depth", "100");
                hashPartToAttributes["Part 2"].Add("Voltage", "240V");

                hashPartToAttributes["Part 3"].Add("Voltage", "110V");
                hashPartToAttributes["Part 3"].Add("Bandwidth", "25");
                hashPartToAttributes["Part 3"].Add("Frequency", "5");
                hashPartToAttributes["Part 3"].Add("Height", "900");

                hashPartToAttributes["Part 4"].Add("Width", "150");
                hashPartToAttributes["Part 4"].Add("Height", "740");
                hashPartToAttributes["Part 4"].Add("Depth", "920");
                hashPartToAttributes["Part 4"].Add("Voltage", "240V");
                hashPartToAttributes["Part 4"].Add("Bandwidth", "40");
                hashPartToAttributes["Part 4"].Add("Frequency", "5");
            }

            // The complete set of all attributes (column headings)

            List<string> attributeKeys = new List<string>() {
                "Width", "Height", "Depth", "Voltage", "Bandwidth", "Frequency"
            };

            // Now construct a row for each part.

            List<List<string>> rows = new List<List<string>>();

            foreach (string part in hashPartToAttributes.Keys)
            {
                List<string> row = new List<string>() { part };

                foreach (string key in attributeKeys)
                {
                    Dictionary<string, string> attributes = hashPartToAttributes[part];

                    if (attributes != null && attributes.ContainsKey(key))
                    {
                        row.Add(attributes[key]);
                    }
                    else
                    {
                        row.Add(null);
                    }
                }

                rows.Add(row);
            }           

            // Print out headings.

            Console.Write("{0, -10}", "Part");

            foreach (string heading in attributeKeys)
            {
                Console.Write("{0, -10}", heading);
            }

            Console.WriteLine();
            Console.WriteLine();

            // Print out the rows

            foreach (List<string> row in rows)
            {
                foreach (string item in row)
                {
                    if (item != null)
                    {
                        Console.Write("{0, -10}", item);
                    }
                    else
                    {
                        Console.Write("{0, -10}", "-");
                    }
                }

                Console.WriteLine();
            }
        }
    }
}

A trivial LINQ statement doesn't exist, but you can use the following:

hashPartToAttributes.Select(
    p => new [] { p.Key }.Concat(
        attributeKeys.GroupJoin(p.Value, ak => ak, a => a.Key,
            (ak, a) => a.Select(x => x.Value).SingleOrDefault())
                     .DefaultIfEmpty())
                         .ToArray()
                           )

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