Home > Software engineering >  Linq query string array inside List of strings
Linq query string array inside List of strings

Time:10-28

Hey all I am trying to query for the string number thats in the first position inside my List:

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" }
};

And the Linq I am using:

List<string> d = idMainDescriptionIcon[0][0]
  .Where(x => x.StartsWith("202"))
  .Select(x => x)
  .ToList();

I am getting an error on the idMainDescriptionIcon[0][0] stating:

Error CS1061 'char' does not contain a definition for 'StartsWith' and no accessible extension method 'StartsWith' accepting a first argument of type 'char' could be found (are you missing a using directive or an assembly reference?)

The D should have the values of "202", "Thunderstorm", "thunderstorm with heavy rain", "11".

And this is where I am stuck at. Not sure how to go about fixing this error?

UPDATE #1

When removing the [0][0] and replacing it with just one [0] this is the return I get:

enter image description here

CodePudding user response:

The problem here is idMainDescriptionIcon[0][0], which is referring to a single string here. Iterating over it would be iterating over characters in the string, which is why you get the error 'char' does not contain a definition for 'StartsWith'

What you would need is the following

var d = idMainDescriptionIcon
  .Where(x => x[0].StartsWith("202"))
  .SelectMany(x => x)
  .ToList();

You need to query the entire idMainDescriptionIcon such that the first element of the inner array starts with "202".

Alternatively,

var d = idMainDescriptionIcon
  .FirstOrDefault(x => x[0].StartsWith("202"))
  .ToList();

Output

enter image description here

  • Related