【问题标题】:Filtering rows of a 2D String matrix by string value按字符串值过滤二维字符串矩阵的行
【发布时间】:2015-01-06 15:56:34
【问题描述】:

所以我有一个定义为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
...

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

我了解使用 LINQ 可能是一种可能性。虽然我不熟悉,但我尝试了以下方法,但是没有进行过滤。

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

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

【问题讨论】:

  • 您的代码看起来不错。你确定column_index 是正确的吗?您是否尝试过设置断点并检查 data_set_examples 中的数据以确保它是您认为的那样?
  • 你如何证明这一点:“但是没有进行过滤”?
  • 为什么不创建一个类来保存数据、当前矩阵行所保存的内容,然后从中创建一个 List 或任何 IEnumerable 呢?这绝对是反面向对象的。过滤、转换等会容易得多。
  • 我如何检查: foreach (string[] s in result) { Console.WriteLine(s); }
  • 问题在你检查,检查这个看看结果foreach (string[] s in result) { Console.WriteLine(string.Join(",", s)); }

标签: c# .net arrays linq jagged-arrays


【解决方案1】:

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

当你使用时

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();
}

【讨论】:

  • 好的,谢谢您指出这一点。这就是问题所在。它奏效了。
【解决方案2】:

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

 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 2017-04-18
    • 2023-03-28
    • 2011-08-14
    • 1970-01-01
    相关资源
    最近更新 更多