使用“包含”查询在C#中的列表
在我的代码,我有“sourceElements”是一种类型的使用“包含”查询在C#中的列表<Key-Value>
List<KeyValuePair<string, string>>.
我需要查询,如果该列表的键包含特定值,i尝试这样:
sourceElements.Add(new KeyValuePair<string, string>("t","t"));
sourceElements.Add(new KeyValuePair<string, string>("test", "test"));
sourceElements.Add(new KeyValuePair<string, string>("t1", "t2"));
if (sourceElements.All(x => x.Key.Contains("test", StringComparer.InvariantCultureIgnoreCase))
{
// do some stuff here
}
但是编译器报告“类型参数不能从使用推断”。
任何想法在代码中不正确的东西?
此代码应该是功能(在LINQPad不给错误)
List<KeyValuePair<string, string>> sourceElements = new List<KeyValuePair<string, string>>();
sourceElements.Add(new KeyValuePair<string, string>("t","t"));
sourceElements.Add(new KeyValuePair<string, string>("test", "test"));
sourceElements.Add(new KeyValuePair<string, string>("t1", "t2"));
if (sourceElements.All(x => x.Key.ToLowerInvariant().Contains("test")))
{
// do some stuff here
}
所以,如果你注释掉键与T和T1的if
- 块中的代码将执行
感谢answer.what区别呢,如果将我的列表字典?有什么好处? –
真的没有太大区别。只是更容易添加值(根据我)因为它会是'sourceElements.Add(“t”,“t”);'而不是。字典必须包含唯一的密钥。 – NoLifeKing
啊好的。保存一些长长的代码。谢谢。有道理1 –
这里的问题是在String
上没有方法Contains
,它采用那些参数类型。 Contains
只有一个超载,它需要String
类型的单个参数。
我相信你正在寻找方法Index(string, StringComparison)
if (sourceElements.All(x => x.Key.IndexOf("test", StringComparison.InvariantCultureIgnoreCase) >= 0))
如果你想在原来的代码工作,你可以添加一个扩展方法,这给String
有这样的过载的外观。
bool Contains(this string str, string value, StringComparison comp) {
return str.IndexOf(value, comp) >= 0;
}
绝对!感谢你的回答。但在我的情况下,我如何使用“包含”呢? IndexOf工作良好,但需要知道如何使用contains来检查我的字符串是否在其中? –
@nowhewhomustnotbenamed当'IndexOf'返回的值是'> = 0'那么它包含您搜索 – JaredPar
感谢扩展方法的字符串。工作得很好:) –
static void Main(string[] args)
{
List<KeyValuePair<string, string>> sourceElements = new List<KeyValuePair<string, string>>();
sourceElements.Add(new KeyValuePair<string, string>("t", "t"));
sourceElements.Add(new KeyValuePair<string, string>("test", "test"));
sourceElements.Add(new KeyValuePair<string, string>("t1", "t2"));
if (sourceElements.All(x =>x.Key.Contains("test")))
{
// do some stuff here
}
}
您正在检查一个布尔值为“0”。 '.contains'将返回'true'或'false' – NoLifeKing
@NoLifeKing:yup。改变了! –
是否可以将数据结构更改为'Dictionary'而不是? –
NoLifeKing