Сортировка строк в файле зависит от содержимого самого файла в c# - PullRequest
0 голосов
/ 28 мая 2020

Содержимое строки в моем файле отформатировано следующим образом:

Ref.,ID,Firstname,Secondname,City

Вот мой файл:

1,4234,Firstname1,Secondname1,City1
2,5647,Firstname2,Secondname2,City2
3,1657,Firstname3,Secondname3,City3
4,3898,Firstname4,Secondname4,City4

Теперь я хочу отсортировать его по идентификатору и поместить его снова в файле, например:

3,1657,Firstname3,Secondname3,City3
4,3898,Firstname4,Secondname4,City4
1,4234,Firstname1,Secondname1,City1
2,5647,Firstname2,Secondname2,City2

Примечание: вся строка является строковой переменной.

Так есть ли способ сделать это?

Вот мой код :

int counter = 0;
string ln; //Each line in file per loop   Ex:1,8957,Firstname,lastname,city

using (StreamReader file = new StreamReader(filePath))
{
    Console.WriteLine("Records in the file" + Environment.NewLine);

    Console.WriteLine("Ref,First name,Second name,City" + Environment.NewLine);

    while ((ln = file.ReadLine()) != null)
    {
        Console.WriteLine(ln + Environment.NewLine);

        /*
        So here i need to sort the lines in the file, which written hard coded in the file before spliting it.
        */

        //split the current line (comma separated) into array of strings with Ref,Id,first name, last name and city respectively
        listLineElements = ln.Split(',').ToList();

        //get city (4th elemnt in the array)
        Student student = new Student(listLineElements[0], listLineElements[1], listLineElements[2], listLineElements[3], listLineElements[4]);

        //for each line call addIndex to check whether index is new? or add it to the secondary index list?
        addIndex(student.getCity(), ln);

        counter++; //counter for the number of read lines
    }
    file.Close();
}

Ответы [ 2 ]

5 голосов
/ 28 мая 2020

Вы можете сделать что-то вроде этого:

string[] lines = File.ReadAllLines(filePath);

string[] sortedLines = lines
    .Select(s => new
    {
        Line = s,
        SortKey = int.Parse(s.Split(',')[1])
    })
    .OrderBy(sl => sl.SortKey)
    .Select(sl => sl.Line)
    .ToArray();

File.WriteAllLines(filePath, sortedLines);

Демо скрипка: https://dotnetfiddle.net/g8M8nQ

2 голосов
/ 28 мая 2020

Один из вариантов - сохранить каждую строку как более организованный пользовательский объект Info, а затем использовать OrderBy для их сортировки. Класс может быть настроен как ...

class Info{
  public int Ref { get; set; };
  public int ID { get; set; };
  public string FirstName { get; set; };
  public string SecondName { get; set; };
  public string City { get; set; };

  Info(int ref, int id, string first, string second, string city)
  {
    Ref = ref; ID = id; FirstName = first; SecondName = second; City = city;
  }
}

Затем для каждой строки вы можете создать один из этих объектов Info с помощью ...

string[] items = line.split(',');
Info lineInfo = new Info(Int32.Parse(items[0]),Int32.Parse(items [1]),items [2],items[3],items[4]);

Как только у вас будет массив / список этих объектов Info, вы можете отсортировать их, используя OrderBy

IEnumerable<Info> query = infoList.OrderBy(info => info.ID);

. Если вы намерены переписать отсортированную группу информации из строк обратно в файл, вы можете просто пройти через этот массив / перечислить и объединить каждое поле в строку.

foreach(Info info in query)
{
    file.WriteLine(info.Ref + "," + info.ID + "," + info.FirstName + "," + info.SecondName + "," + info.City);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...