简体   繁体   English

C#linq从字典中选择

[英]C# linq Select from Dictionary

How to get part of dictionary, which keys are true for some conditionals. 如何获得字典的一部分,哪些键对于某些条件是正确的。 For example, I have a dictionary. 例如,我有字典。

var dictionary = new Dictionary<string, int>();
dictionary["first"] = 1;
dictionary["firstOfSecond"] = 2;
dictionary["second"] = 3;
dictionary["first-and-second"] = 4;

I need part of this dictionary, which keys are started from "first". 我需要这本词典的一部分,其中的键从“第一”开始。 How to do it? 怎么做?

var result = dictionary.Where(x => x.Key.Contains("first"));

要么

var result = dictionary.Where(x => x.Key.StartsWith("first"));
var result = dictionary.Where(x => x.Key.StartsWith("first", StringComparison.OrdinalIgnoreCase));

所有以first开头的键,但不包括任何大小写。

You can use StartWith method of string: 您可以使用字符串的StartWith方法:

var result= dictionary.Where(x => x.Key.StartWith("first"));

StartWith has an overload where you can pass the StringComparison you want to use, eg, the current culture or the invariant culture, word or ordinal sort rules, and be case-sensitive or case-insensitive. StartWith有一个重载,您可以在其中传递您要使用的StringComparison ,例如,当前区域性或不变区域性,单词或序数排序规则,并且区分大小写或不区分大小写。

dictionary.Keys.Where(t => t.StartsWith(“ first”))。ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM