C# Sortable collection which allows duplicate keys

前端 未结 16 2177
旧巷少年郎
旧巷少年郎 2020-11-28 10:06

I am writing a program to set a sequence in which various objects will appear in report. The sequence is the Y position (cell) on Excel spreadsheet.

A demo part of co

16条回答
  •  余生分开走
    2020-11-28 10:57

    The problem is that the data structure design doesn't match the requirements: It is necessary to store several Headers for the same XPos. Therefore, SortedList should not have a value of Header, but a value of List

    . It's a simple and small change, but it solves all problems and avoids creating new problems like other suggested solutions (see explanation below):

    using System;
    using System.Collections.Generic;
    
    namespace TrySortedList {
      class Program {
    
        class Header {
          public int XPos;
          public string Name;
        }
    
        static void Main(string[] args) {
          SortedList> sortedHeaders = new SortedList>();
          add(sortedHeaders, 1, "Header_1");
          add(sortedHeaders, 1, "Header_2");
          add(sortedHeaders, 2, "Header_3");
          foreach (var headersKvp in sortedHeaders) {
            foreach (Header header in headersKvp.Value) {
              Console.WriteLine(header.XPos + ": " + header.Name);
            }
          }
        }
    
        private static void add(SortedList> sortedHeaders, int xPos, string name) {
          List
    headers; if (!sortedHeaders.TryGetValue(xPos, out headers)){ headers = new List
    (); sortedHeaders[xPos] = headers; } headers.Add(new Header { XPos = xPos, Name = name }); } } } Output: 1: Header_1 1: Header_2 2: Header_3

    Please note that adding a "funny" key, like adding a random number or pretending that 2 XPos with the same value are different lead to many other problems. For example it becomes difficult or even impossible to remove a particular Header.

    Also note that the sorting performance is much better if only few List

    have to be sorted than every Header. Example: If there are 100 XPos and each has 100 headers, 10000 Header need to be sorted as opposed to 100 List
    .

    Of course, also this solution has a disadvantage: If there are many XPos with only 1 Header, as many Lists need to be created, which is some overhead.

提交回复
热议问题