我需要实现一个
Dictionary<int, Tuple<string, double, double>>
在VS2013的C#中。
字典持有
Dictionary<3, Tuple<"id1", 65.97, 9.8>>
我需要为元组中的每个元素命名。例如,
Dictionary<3, Tuple<id:id1, value1:65.97, value2:9.8>>
我需要按名称搜索元组中的元素以获取其值。
任何帮助将不胜感激。
答案 0 :(得分:1)
定义一个类并使用它而不是元组。
public class ObjectName {
public string id { get; set; }
public double value1 { get; set; }
public double value2 { get; set; }
public ObjectName(string id, double val1, double val2) {
this.id = id;
this.value1 = val1;
this.value2 = val2;
}
}
然后在你的代码中:
Dictionary<3, new ObjectName("id1", 65.97, 9.8 }>
答案 1 :(得分:1)
坚持下去:
public sealed class MyTuple : IEquatable<MyTuple>
{
private readonly string _Id;
private readonly double _Value1;
private readonly double _Value2;
public string Id { get { return _Id; } }
public double Value1 { get { return _Value1; } }
public double Value2 { get { return _Value2; } }
public MyTuple(string Id, double Value1, double Value2)
{
_Id = Id;
_Value1 = Value1;
_Value2 = Value2;
}
public override bool Equals(object obj)
{
if (obj is MyTuple)
return Equals((MyTuple)obj);
return false;
}
public bool Equals(MyTuple obj)
{
if (obj == null) return false;
if (!EqualityComparer<string>.Default.Equals(_Id, obj._Id)) return false;
if (!EqualityComparer<double>.Default.Equals(_Value1, obj._Value1)) return false;
if (!EqualityComparer<double>.Default.Equals(_Value2, obj._Value2)) return false;
return true;
}
public override int GetHashCode()
{
int hash = 0;
hash ^= EqualityComparer<string>.Default.GetHashCode(_Id);
hash ^= EqualityComparer<double>.Default.GetHashCode(_Value1);
hash ^= EqualityComparer<double>.Default.GetHashCode(_Value2);
return hash;
}
public override string ToString()
{
return String.Format("{{ Id = {0}, Value1 = {1}, Value2 = {2} }}", _Id, _Value1, _Value2);
}
}
它具有可比性,可用于LINQ表达式。