【问题标题】:Return a List from Tuple of dual values via Linq query通过 Linq 查询从对偶值的元组返回列表
【发布时间】:2018-06-09 07:55:37
【问题描述】:

我有一个具有双重值的元组列表:

List<Tuple<string, string>> Descriptions;

我一直在添加内容,就像这样:

Descriptions.Add (new Tuple<string, string> ("max", "some description"));
Descriptions.Add (new Tuple<string, string> ("joe", "some description"));
Descriptions.Add (new Tuple<string, string> ("jane", "some description"));
Descriptions.Add (new Tuple<string, string> ("max", "some other description"));

我想使用 Linq 检索一个列表,其中元组中的 Item1 是一个特定值,例如 "max"。我可以使用这段代码:

var s = Descriptions.Where (x => x.Item1 == "max");

但这会给 s 分配一个元组列表,这是我不想要的。我只想要一个描述字符串的列表,也就是说,它应该返回一个list&lt;string&gt;,其中包含与Item1字符串"max"关联的所有描述。

【问题讨论】:

标签: c# list linq collections tuples


【解决方案1】:

使用Select:

var s = Descriptions.Where (x => x.Item1 == "max").Select(y => y.Item2);

这将返回一个IEnumerable&lt;string&gt;。如果要列表,还需要在末尾加上ToList

var s = Descriptions.Where (x => x.Item1 == "max").Select(y => y.Item2).ToList();

或者你可以使用查询语法:

var s = from d in Descriptions
        where d.Item1 == "max"
        select d.Item2;

这与第一个选项相同。事实上,编译器会将查询语法翻译成 linq 的扩展方法。

【讨论】:

    【解决方案2】:

    Where() 之后,您可以使用Select() 方法仅获取description,在您的情况下将是Item2 of Tuple,您需要这样做:

    var s = Descriptions.Where(x => x.Item1 == "max")
                        .Select(x=>x.Item2); // projects only Description
    

    这将返回IEnumerable&lt;string&gt; 形式的所有元素,其中Item1 具有值"max",如果你真的想将它作为List&lt;string&gt;,那么你可以在最后添加ToList() 方法调用。

    希望对你有帮助。

    【讨论】:

    • 谢谢,成功了。然而,另一个答案更适合我的情况。
    • 是的,很高兴为您提供帮助,这是您的决定:) 两者都可以。
    【解决方案3】:

    如果您不使用其他解决方案,请尝试使用字典而不是元组列表。从您的内容的外观来看,这可能是您想要的更多(仅当您的名字是唯一的)。

    Dictionary<string, string> NameDesc = new Dictionary<string, string>();
                NameDesc.Add("max", "desc1");
                NameDesc.Add("tim", "desc2");
    
                var description = NameDesc["max"];
                var maxExists = NameDesc.ContainsKey("max");
    

    【讨论】:

    • 该问题清楚地在样本数据中两次声明了值“max”。字典不会这样……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2021-07-11
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多