テキストファイルからデータを並べ替えて、別のテキストファイルに保存したい
これが私のテキストファイル「employee.txt」です。「従業員コード」を使用してデータを並べ替えたい
従業員コード:107名:swapnil名前:dehjhja電話番号:6727672
従業員コード:106名:fhsgbf名前:dehjhja電話番号:909888
従業員コード:102名:xyz姓:dehjhja電話番号:098778
テキストファイルからデータを並べ替えて、別のテキストファイルに保存したい
これが私のテキストファイル「employee.txt」です。「従業員コード」を使用してデータを並べ替えたい
従業員コード:107名:swapnil名前:dehjhja電話番号:6727672
従業員コード:106名:fhsgbf名前:dehjhja電話番号:909888
従業員コード:102名:xyz姓:dehjhja電話番号:098778
データを並べ替え可能なエンティティにインポートし、コレクションでsortメソッドを呼び出して(つまりList<T>
)、データを任意の形式にエクスポートする必要があります。
インポート/エクスポートについては、FileHelperslibhttp://www.filehelpers.com/downloads.htmlをお勧めします。
IComparable<>
並べ替えについては、エンティティに実装します。
ICompableの例:
using System;
using System.Collections;
public class Person : IComparable<Person>
{
#region Private Members
private string _firstname;
private string _lastname;
private int _age;
#endregion
#region Properties
public string Firstname
{
get { return _firstname; }
set { _firstname = value; }
}
public string Lastname
{
get { return _lastname; }
set { _lastname = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
#endregion
#region Contructors
public Person (string firstname, string lastname, int age)
{
_firstname = firstname;
_lastname = lastname;
_age = age;
}
#endregion
public override string ToString()
{
return String.Format(“{0} {1}, Age = {2}“, _firstname,
_lastname, _age.ToString());
}
#region IComparable Members
public int CompareTo(Person obj)
{
return _firstname.CompareTo(p2.Firstname);
}
#endregion
}
ファイルの読み取り/書き込みには、File.ReadAllLinesを使用して行を文字列配列に読み取り、File.WriteAllLinesを使用してファイルに書き戻すことができます。これらの関数は、ファイルのすべての開閉を処理するため、ファイルを開く必要はありません。
並べ替えを処理するために、LINQのorderbyキーワードと静的ヘルパー関数GetEmployeeCode
を使用してEmployeeCodeを取得できます。ヘルパー関数は次のように定義できます。
public static int GetEmployeeCode(string line)
{
// Get the substring starting after "Employee code:"
// ... and stopping at the first space.
string employeeCode = line.Substring(14).Split(' ')[0];
int code;
Int32.TryParse(employeeCode, out code);
return code;
}
次のコードは、ファイル内のすべての行をEmployeeCodeの昇順で並べ替えてから、新しいファイルに書き込みます。
string[] lines = File.ReadAllLines(@"C:\original.txt");
// Sort the rows in lines by EmployeeCode
lines = (from line in lines
orderby GetEmployeeCode(line) ascending
select line).ToArray();
File.WriteAllLines(@"C:\sorted.txt", lines);