按字符串值过滤二维字符串矩阵的行

Filtering rows of a 2D String matrix by string value

所以我有一个定义为 String[][] data_set_examples 的二维数组,它包含以下数据:

Sunny,Hot,High,Weak,No
Sunny,Hot,High,Strong,No
Overcast,Hot,High,Weak,Yes
Rain,Mild,High,Weak,Yes
Rain,Cool,Normal,Weak,Yes
...

我想按特定值过滤行,例如包含 "Hot" 的行(按列索引 1)

我知道一种可能是使用 LINQ。虽然我不熟悉,但我尝试了以下操作,但是没有进行过滤。

var result = from u in data_set_examples
                         where u[column_index].Equals(attribute_value)
                         select u;

我做错了什么?还有其他方法吗?

你的代码看起来不错,我认为问题出在你检查过滤结果的方式上。

当您使用

foreach (string[] s in result) 
{ 
    Console.WriteLine(s); 
}

你正在写 string[]

的类型名称

但是您应该在结果 (string[][])

中看到那些 string[]

你可以通过两种方式做到这一点

foreach (string[] s in result)
{
     //concatenate all the values in s
     Console.WriteLine(string.Join(",", s));
}

foreach (string[] s in result)
{
    //iterate through strings in s and print them
    foreach (string s1 in s)
    {
        Console.Write(s1 + " ");
    }
    Console.WriteLine();
}

我试过了,刚刚确认它有效:

 string[][] data_set_examples = new string[][]{
                new string[]{"Sunny", "Hot", "High", "Weak", "No"},
                new string[]{"Sunny", "Hot", "High", "Strong", "No"},
                new string[]{"Overcast", "Hot", "High", "Weak", "Yes"},
                new string[]{"Rain", "Mild", "High", "Weak", "Yes"},
                new string[]{"Rain", "Cool", "Normal", "Weak", "Yes"},
            };
            IEnumerable<string[]> result = from u in data_set_examples
                         where u[1].Equals("Hot")
                         select u;
            foreach (string[] s in result) {
                foreach (string part in s)
                    Console.Write(part + " ");
                Console.WriteLine();
            }
            Console.Read();

生成输出:

Sunny Hot High Weak No
Sunny Hot High Strong No
Overcast Hot High Weak Yes