make it possible to search for a given column
There are several options to implement a search in a CSV file by column.
1. Use DataTable
private DataTable CsvToDataTable(string fileName) { var dt = new DataTable("FileData"); //Если первая строка содержит заголовки столбцов, формируем из нее столбцы таблицы, если нет, придется делать вручную. var header = File.ReadLines(fileName).First(); var colHeaders = header.Split(';'); foreach(var hdr in colHeaders) { dt.Columns.Add(hdr); } //Все строки файла кроме первой заносим в качестве строк таблицы foreach(var row in File.ReadLines(fileName).Skip(1)) { var values = row.Split(';'); dt.Rows.Add(values); } return dt; }
The table is formed, now you can perform a search, for example:
var dt = CsvToDataTable("C:\\test.csv"); var findResult = dt.Select("ColName = 'searchText'");
As a result, we obtain an array from DataRow for which the given condition is fulfilled. Of course, the condition must be written using real column names.
2. We are looking for on the fly without full file download
var colIndex = x;//x - номер интересующего столбца, нумерация с 0 var searchText = "searchText"; //пропускаем первую строку, если в ней заголовки с помощью Skip foreach(var row in File.ReadLines(fileName).Skip(1)) { var values = row.Split(';'); if(values[colIndex] == searchText) { Console.WriteLine("Результат поиска: {0}",stroka); break; } }
In both cases, the trick is that when splitting a string from a CSV file, you cannot use StringSplitOptions.RemoveEmptyEntries so that the column indexes do not change if individual values in the string are omitted, and the source CSV file format must be correct.
3. Is it possible somehow?
Can. There are many different options, these are just examples of a possible implementation, which particular option of all possible uses depends on the specific task.
Править, to edit the text of the question, please use it and add what kind of search is needed. 1. What we are looking for - the row number in which there is a match with the sample, the column number or both, or just the fact of the match. 2. Ideal - attach a minimal example of the source csv-file (no huge one is needed, 3x3 is enough), a sample for the search and the expected result. Then I can quickly complete the answer. - rdorn