Reputation: 763
I need to implement a
Dictionary<int, Tuple<string, double, double>>
in C# in VS2013.
The dictionary holds
Dictionary<3, Tuple<"id1", 65.97, 9.8>>
I need to give a name for each element in the tuple. For example,
Dictionary<3, Tuple<id:id1, value1:65.97, value2:9.8>>
I need to search an element in the tuple by their name to get its value.
Any help would be appreciated.
Upvotes: 1
Views: 92
Reputation: 1029
Define a Class and use that instead of a tuple.
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;
}
}
Then in your code:
Dictionary<3, new ObjectName("id1", 65.97, 9.8 }>
Upvotes: 1
Reputation: 117029
Go with this:
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);
}
}
It's properly comparable and can be used in LINQ expressions.
Upvotes: 1