Reputation: 1555
I want to store two strings in a collection but the combination should be unique eg
'1','2'
'2','1'
'1','2' -> not allowed
'2','3'
Which collection should I use if I want both strings to be keys?
Upvotes: 2
Views: 6403
Reputation: 156948
Use a HashSet<CustomObject>
, with a custom IEqualityComparer
. The comparer makes sure that no entries are allowed with duplicate values. I just wrote a sample implementation, adapt it to your convenience.
HashSet<CustomObject> x = new HashSet<CustomObject>(new XE());
public class CustomObjectEqualityComparer : IEqualityComparer<CustomObject>
{
public bool Equals(CustomObject x, CustomObject y)
{
return x.Var1 == y.Var1 && x.Var2 == y.Var2;
}
public int GetHashCode(string obj)
{
//
}
}
public class CustomObject
{
public string Var1 { get; set; }
public string Var2 { get; set; }
}
Upvotes: 3
Reputation: 8986
Use a HashSet
of KeyValuePair<String, String>
.
For example:
HashSet<KeyValuePair<String, String>> set = new HashSet<KeyValuePair<string, string>>();
set.Add(new KeyValuePair<string, string>("1", "2"));
set.Add(new KeyValuePair<string, string>("1", "2"));
This will produce only one entry in the set.
For reference:
Upvotes: 4
Reputation: 3182
No duplicates returned
static NameValueCollection GetCollection()
{
NameValueCollection collection = new NameValueCollection();
collection.Add("Sam", "Dot Net Perls");
collection.Add("Bill", "Microsoft");
collection.Add("Bill", "White House");
collection.Add("Sam", "IBM");
return collection;
}
static void Main()
{
NameValueCollection collection = GetCollection();
foreach (string key in collection.AllKeys) // <-- No duplicates returned.
{
Console.WriteLine(key);
}
duplicates return
public class ListWithDuplicates : List<KeyValuePair<string, string>>
{
public void Add(string key, string value)
{
var element = new KeyValuePair<string, string>(key, value);
this.Add(element);
}
}
var list = new ListWithDuplicates();
list.Add("rr", "11");
list.Add("rr", "22");
list.Add("rr", "33");
foreach(var item in list)
{
string x = string.format("{0}={1}, ", item.Key, item.Value);
}
Outputs rr=11, rr=22, rr=33.
Upvotes: 0
Reputation: 38598
Try using a custom type and a hashSet collection. For sample:
public class Item : IEqualityComparer<Item>
{
public string Value1 { get; set; }
public string Value2 { get; set; }
public bool Equals(Item x, Item y)
{
return x.Valie1 == y.Value1 && x.Value2 != y.Value2;
}
public int GetHashCode(string obj)
{
// implement
}
}
Use a hashSet
HashSet<Item> set = new HashSet<Item>();
set.Add(new Item() { Value1 = "1", Value2 = "1" });
Upvotes: 1