将文本文件转换为ListCollection和Filter

时间:2016-02-11 12:56:55

标签: c# .net list c#-4.0 collections

我的文本文件包含如下数据:

    FacilityID:   23
    FacilityName: ACME Medical Center
    Facility Location: 
    RecordID:            1661
    Patient:           Kistra Halos
    Gender:            Female
    DOB:               7/20/1955

我必须读取该文件并转换为ListCollection并使用lambda或Linq方式过滤此ListCollection

我在ListCollection中插入数据并使用Linq进行过滤也是如此 检查以下内容:

static void Main(string[] args)
        {

            var PatientList = new List<Patient>();

            PatientList.Add(new Patient() { FacilityID = 23, FacilityName = "Schedule23", FacilityLocation = "M23", RecordID = 11, PatientName = "P23", Gender = "F", DOB = "01-07-1987" }); 



            Console.WriteLine("List Filter LINQ Way:");
            foreach (var v in from p in PatientList
                              where p.PatientName == "P25" && p.FacilityName == "Schedule25"
                              select new { p.PatientName, p.FacilityName })
                Console.WriteLine(v.PatientName + " is " + v.FacilityName);
        } 

1 个答案:

答案 0 :(得分:1)

你可以简单地使用文件阅读器获取文件并使用string.split()将其分解为部分。

using System.IO; //For File

//Take in file
string file = File.ReadAllText("C:/path/to/file.txt");
//Split into each facility
string[] facilities = file.Split(" ======================== ");
foreach(var facility in facilities)
{
    //Split by line
    string[] lines = facility.split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
    //Take each line, split into title & data and remove whitespace
    PatientList.Add(new Patient() {
        FacilityID =        int.Parse(lines[0].Split(":")[1].trim()),
        FacilityName =      lines[1].Split(":")[1].Trim(),
        FacilityLocation =  lines[2].Split(":")[1].Trim(),
        RecordID =          int.Parse(lines[3].Split(":")[1].Trim()),
        PatientName =       lines[4].Split(":")[1].Trim(),
        Gender =            lines[5].Split(":")[1].Trim(),
        DOB =               lines[6].Split(":")[1].Trim() });
}

这假设您的数据格式与示例完全相同,并且文件中没有错误。