从集合中获取元组的值之一? [英] Get Tuple from a collection by one of its values?

查看:63
本文介绍了从集合中获取元组的值之一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以仅通过元组的值之一从集合中获取元组?例如,当我使用此Tuple结构时:

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;} 
}

有没有办法获取所有具有特定项目(Item1或Item2)。我考虑过某种HashMap,因为循环浏览一个元组列表并检查每个元组是否匹配对于大型数据集而言效率很低。

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.

推荐答案

如果您有这样的列表:

List<Tuple<T1, T2>> mylist;

您可以使用LINQ枚举列表中的所有元素,以搜索第一个与条件类似的元素

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.

这篇关于从集合中获取元组的值之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆