程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 使用LINQ讀取分隔符文本文件

使用LINQ讀取分隔符文本文件

編輯:C#入門知識

有時我們會處理一些帶分隔符數據文本文件。例如,使用”,”分隔的數據,如下圖:

linqimage23

然後它們存儲到文本文件有這樣的列:

  • First Name
  • Last Name
  • Job Title
  • City
  • Country

     

    在我們讀取這個文件之前,先建一個實體類:

       1:      /// <summary>
       2:      /// Customer entity
       3:      /// </summary>
       4:      /// Author Petter Liu http://wintersun.cnblogs.com
       5:      public class Customer
       6:      {
       7:          public string Firstname { get; set; }
       8:          public string Lastname { get; set; }
       9:          public string JobTitle { get; set; }
      10:          public string City { get; set; }
      11:          public string Country { get; set; }
      12:      }


    接著我們使用LINQ讀取整個文件:

       1:              var query = from line in File.ReadAllLines(filePath)
       2:                          let customerRecord = line.Split(,)
       3:                          select new Customer()
       4:                          {
       5:                              Firstname = customerRecord[0],
       6:                              Lastname = customerRecord[1],
       7:                              JobTitle = customerRecord[2],
       8:                              City = customerRecord[3],
       9:                              Country = customerRecord[4]
      10:                          };
      11:              foreach (var item in query)
      12:              {
      13:                  Console.WriteLine("{0}, {1}, {2}, {3}, {4}"
      14:                    , item.Firstname, item.Lastname, item.JobTitle, item.City, item.Country);
      15:              }

     

    要讀取可以帶條件的記錄也可以,我們filter出Country是UK:

       1:              var query = from c in
       2:                              (from line in File.ReadAllLines(filePath)
       3:                               let customerRecord = line.Split(,)
       4:                               select new Customer()
       5:                               {
       6:                                   Firstname = customerRecord[0],
       7:                                   Lastname = customerRecord[1],
       8:                                   JobTitle = customerRecord[2],
       9:                                   City = customerRecord[3],
      10:                                   Country = customerRecord[4]
      11:                               })
      12:                          where c.Country == "UK"
      13:                          select c;

     

    另一例子:

       1:              var query = from c in
    
    							
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved