-2

There is a 1.csv file

name1;5547894;bnt652147
name2;5546126;bnt956231
name3;5549871;nhy754497

How in fast and elegant way, may be in one line, read this file and add separated values to 2d array?

And then, how we can easily and quickly seach for some string in that array?

lfreedoml
  • 55
  • 6
  • For true CSV file parsing (i.e. which takes quotes & escape characters into account), use `Microsoft.VisualBasic.FileIO.TextFieldParser` per https://stackoverflow.com/a/3508572/361842 – JohnLBevan Jun 30 '17 at 15:23

1 Answers1

0

Using an Array of arrays or a List of arrays is much easier, but a 2D array can be done.

For a List of arrays:

var listInput = File.RealAllLines("1.csv").Select(line => line.Split(';')).ToList();

To find any rows containing a string:

var find = "5549871";
var ContainingRows = listInput.Where(r => r.Any(s => s.Contains(find))).ToList();

To find a row containing an exact match:

var EqualRows = listInput.Where(r => r.Any(s => s == find)).ToList();

If you know there is just one match, you can replace ToList() with First().

If you know more about your search, you could create an index (Dictionary) instead to speed up retrieval.

Unfortunately, there aren't any corresponding 2D array creation features, you must know the size to create it.

var array2d = new string[listInput.Length, 3];
for (int row = 0; row < listInput.Length; ++row) {
    for (int col = 0; col < 3; ++col)
        array2d[row, col] = listInput[row][col];
}

Searching it isn't going to be fast unless you create some type of index, but also easy.

var findrow = -1;
for (int row = 0; row < array2d.GetUpperBound(0); ++row) {
    for (int col = 0; col < array2d.GetUpperBound(1); ++col) {
        if (array2d[row,col].Contains(find)) {
            findrow = row;
            break;
         }
    }
}
NetMage
  • 26,163
  • 3
  • 34
  • 55