使用哪个c#集合而不是List <KeyValuePair <string,double >>?

fre*_*one 6 c# collections data-structures

我想存储数据,如

{
 {"apple",15   }
 {"pear",12.5  }
 {"", 10       }
 {"", 0.45     }
}
Run Code Online (Sandbox Code Playgroud)

数据将绘制在条形图上(字符串将是图例,double将是值)插入顺序很重要.Perfs并不重要. 字符串可以重复或为空.(值也可能重复)

我需要获得最小值和最大值(如果可能的话,很容易)来设置比例.

我用

List<KeyValuePair<string, double>> data = new List<KeyValuePair<string, double>>();
data.Add(new KeyValuePair<string,double>("",i));
Run Code Online (Sandbox Code Playgroud)

相当无聊和难以理解.有更清洁的方法吗?

StringDoubleCollection data = new StringDoubleCollection();
data.add("apple",15);
data.add("",10);

double max = data.values.Max(); 
double min = data.values.Min();
Run Code Online (Sandbox Code Playgroud)

如果不是如何获得最大值List<KeyValuePair<string, double>>没有太多的麻烦

NameValueCollection看起来不错,但<string,string>我需要一个<string,double>

谢谢

as-*_*cii 5

您可以创建如下所示的类:

class X
{
     public string Name { get; set; }
     public double Value { get; set; }

     // name is an optional parameter (this means it can be used only in C# 4)
     public X(double value, string name = "")
     {
         this.Name = name;
         this.Value = value;
     }

     // whatever
}
Run Code Online (Sandbox Code Playgroud)

然后使用带有选择器的LINQ获取最大值和最小值:

var data = new List<X>();
data.Add(new X(35.0, "Apple"))
data.Add(new X(50.0));

double max = data.Max(a => a.Value);
double min = data.Min(a => a.Value);
Run Code Online (Sandbox Code Playgroud)

编辑:如果上面的代码似乎仍然不可读,请尝试使用运算符改进它,以便您只想获得值.

// Inside X class...
public static implicit operator X(double d)
{
    return new X(d);
}

// Somewhere else...
data.Add(50.0);
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 2

要确定您真正想要哪种数据结构,让我们看看您的使用模式。

  • 插入顺序很重要。
  • 您无法通过密钥访问您的物品。
  • 你想要最小值和最大值。

堆提供最小最大值,但不保留顺序。基于哈希的字典也不保留顺序。对于您的数据结构来说,列表实际上是一个不错的选择。它可用并提供出色的支持。

您可以通过为数据结构和条形数据定义类来美化您的代码。您还可以向集合添加最小/最大功能。注意:我没有使用 Linq Min/Max 函数,因为它们返回最小值而不是最小元素

public class BarGraphData {
    public string Legend { get; set; }
    public double Value { get; set; }
}

public class BarGraphDataCollection : List<BarGraphData> {
    // add necessary constructors, if any

    public BarGraphData Min() {
        BarGraphData min = null;
        // finds the minmum item
        // prefers the item with the lowest index
        foreach (BarGraphData item in this) {
            if ( min == null )
                min = item;
            else if ( item.Value < min.Value )
                min = item;
        }
        if ( min == null )
            throw new InvalidOperationException("The list is empty.");
        return min;
    }

    public BarGraphData Max() {
        // similar implementation as Min
    }
}
Run Code Online (Sandbox Code Playgroud)