I have a list of tuples, the objects in the tuple are both the same type. The data structure of a list of tuples is needed until we get to error handling. To optimize error handling, I would like to flatten the tuples into a single list to allow for duplicate checking:
For instance if I had List<Tuple<string,string>>() (my types are more complex but the idea should hold):
[<"Tom","Dick">, <"Dick","Harry">, <"Bob","John">]
I would like to end up with:
["Tom", "Dick", "Harry", "Bob", "John"]
I know I could do this with:
List<string> stringList = List<string>();
Foreach(var item in tupleList){
stringList.Add(item.Item1);
stringList.Add(item.Item2);
}
stringList = stringList.Distinct();
But I am hoping for a more efficient way, perhaps something built into Linq. There is no guarantee of duplicates, but due to the performance cost of error handling, I would rather handle each only once.
If you need distinct items without order - use HashSet:
HashSet<string> stringList = new HashSet<string>();
foreach(var item in tupleList){
stringList.Add(item.Item1);
stringList.Add(item.Item2);
}
You can do similar code with LINQ, but it will not be faster (and probably not better looking as you need to convert Tuple to enumerable for most operations). You can try Aggregate if you really looking for LINQ.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With