Get Tuple from a collection by one of its values?

让人想犯罪 __ 提交于 2019-12-04 07:00:00

问题


Is there a way to get a Tuple from a collection by only one of the Tuple's values? For example when I use this Tuple struct:

public struct Tuple<T1, T2> {
    public readonly T1 Item1;
    public readonly T2 Item2;
    public Tuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2;} 
}

Is there a way to get all Tuples that have a specific item (Item1 or Item2). I thought about some kind of HashMap since looping through a list of tuples and checking each tuple for a match is quite inefficient for large datasets.


回答1:


If you have a list like this:

List<Tuple<T1, T2>> mylist;

You can use LINQ to enumerate all the elements of the list searching for the first one matching a condition like this:

var myValue = mylist.FirstOrDefault((t) => t.Item1 == "MyKey");

I should add, however, that this is not really good design. See comments for details, but in my own opinion, Tuples are generally not good for serious tasks because the elements are not named. The more unnamed elements you have in your data structure the harder your code will be to read. I use dictionaries for tasks like this all the time. I don't think you should be reluctant to use a dictionary instead in this case.




回答2:


Unfortunately it appears .Net does not include any type of space efficient collection class that is based on a key extracted from the objects stored. The KeyedCollection<> class has the right interface, but internally stores the keys and values separately. I would suggest you would need to create your own class that implements ILookup<> but that allows dynamic modification (unfortunately the built-in Lookup class doesn't).




回答3:


If you have List of Tuple<T1, T2> objects, you can use LINQ to get a new list containing the ones you want by specifying desired conditions. Here is an example using Tuple<int, string> objects:

 List<Tuple<int, string>> originalList = new List<Tuple<int, string>>();

 originalList.Add(new Tuple<int, string>(1, "Tom"));
 originalList.Add(new Tuple<int, string>(2, "Jim"));
 originalList.Add(new Tuple<int, string>(3, "Bob"));
 originalList.Add(new Tuple<int, string>(1, "Ted"));
 originalList.Add(new Tuple<int, string>(3, "Hal"));
 originalList.Add(new Tuple<int, string>(1, "Zim"));
 originalList.Add(new Tuple<int, string>(3, "Jed"));

List<Tuple<int, string>> filteredList = originalList.Where(t => t.Item1 == 3).ToList();

// filteredList contains these:
// (3, "Bob")
// (3, "Hal")
// (3, "Jed")

List<Tuple<int, string>> anotherFilteredList = originalList.Where(t => t.Item2.StartsWith("J")).ToList();

// anotherFilteredList contains these:
// (2, "Jim")
// (3, "Jed")


来源:https://stackoverflow.com/questions/48450089/get-tuple-from-a-collection-by-one-of-its-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!