首页 > 解决方案 > 字符串列表中的Linq查询字符串数组

问题描述

嘿,我正在尝试查询列表中第一个位置的字符串编号:

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' 的定义,并且找不到接受“char”类型的第一个参数的可访问扩展方法“StartsWith”(您是否缺少 using 指令或程序集引用?)

D 的值应为"202", "Thunderstorm", "thunderstorm with heavy rain", "11"

这就是我坚持的地方。不确定如何解决此错误?

更新#1

当删除 [0][0] 并用一个 [0] 替换它时,这是我得到的回报:

在此处输入图像描述

标签: c#listlinq

解决方案


这里的问题是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();

输出

在此处输入图像描述


推荐阅读