字符串列表中的Linq查询字符串数组
Posted
技术标签:
【中文标题】字符串列表中的Linq查询字符串数组【英文标题】:Linq query string array inside List of strings 【发布时间】:2021-12-11 10:45:01 【问题描述】:嘿,我正在尝试查询列表中第一个位置的字符串编号:
List<string[]> idMainDescriptionIcon = new List<string[]>()
// [ID] [Main] [Description] "XX[d=day or n=night]"
new string[4] "200", "Thunderstorm", "thunderstorm with light rain", "11" ,
new string[4] "201", "Thunderstorm", "thunderstorm with rain", "11" ,
new string[4] "202", "Thunderstorm", "thunderstorm with heavy rain", "11" ,
new string[4] "210", "Thunderstorm", "light thunderstorm", "11" ,
new string[4] "211", "Thunderstorm", "thunderstorm", "11"
;
还有我正在使用的 Linq:
List<string> d = idMainDescriptionIcon[0][0]
.Where(x => x.StartsWith("202"))
.Select(x => x)
.ToList();
我在idMainDescriptionIcon[0][0]
上收到错误声明:
错误 CS1061 'char' 不包含 'StartsWith' 的定义和 没有可访问的扩展方法“StartsWith”接受第一个参数 可以找到“char”类型的(您是否缺少 using 指令或 汇编参考?)
D 的值应该是"202", "Thunderstorm", "thunderstorm with heavy rain", "11"
。
这就是我所困的地方。不确定如何修复此错误?
更新 #1
当删除 [0][0] 并仅用一个 [0] 替换它时,这是我得到的回报:
【问题讨论】:
idMainDescriptionIcon[0][0]
得到一个太多 [0]。
感谢@Jawad 的回复。我已更新我的 OP 以显示仅使用 [0] 而不是 [0][0] 时得到的结果。
【参考方案1】:
这里的问题是idMainDescriptionIcon[0][0]
,这里指的是单个字符串。迭代它会迭代字符串中的字符,这就是为什么你得到错误'char' does not contain a definition for 'StartsWith'
您需要的是以下内容
var d = idMainDescriptionIcon
.Where(x => x[0].StartsWith("202"))
.SelectMany(x => x)
.ToList();
您需要查询整个idMainDescriptionIcon
,使得内部数组的第一个元素以“202”开头。
或者,
var d = idMainDescriptionIcon
.FirstOrDefault(x => x[0].StartsWith("202"))
.ToList();
输出
【讨论】:
阿努成功了!它现在应该可以工作了:) 您对SelectMany()
的看法可能也是正确的,其中操作人员需要直接收集字符串,尽管这是请求数据的一种稍微不寻常的方式。
@JoelCoehoorn 有什么特别的理由在您的编辑中更喜欢x[0]
而不是First()
?
StartsWith()
在Where()
中与SelectMany()
的组合可能会导致意外输出,具体取决于@StealthRT 的尝试。将Where()
替换为FirstOrDefault()
可能会更好。
@Corey 完成,感谢您的建议以上是关于字符串列表中的Linq查询字符串数组的主要内容,如果未能解决你的问题,请参考以下文章
用于检查字符串列表/数组中的字符串的 C# 最佳实践 (LINQ) [关闭]