To read a separator text file using LINQ

Source: Internet
Author: User
Tags split

Sometimes we deal with delimited data text files. For example, use the data delimited by "," and here's how to read a separator text file using LINQ

the following figure:   Then they are stored in a text file with columns: The code is as follows: The first name is last name Job Title City Country     Before we read this file, we build an entity class:   code is as follows :///<summary>  ///Customer entity///</summary> public class customer{public string Firstname {get; Set public string Lastname {get; set;} public string JobTitle {get; set;} public string City {get; Country {get; set;}}     Then we read the entire file using LINQ: The code is as follows: var query = from lines in File.ReadAllLines (filePath)  let CustomerRecord = line . Split (', ') select New Customer ()  {Firstname = customerrecord[0], Lastname = customerrecord[1],  jobtitle = cus TOMERRECORD[2], city = customerrecord[3], Country = customerrecord[4]};  foreach (var item in query) {Console.WriteLine ("{0}, {1}, {2}, {3}, {4}"  , item. Firstname, item. Lastname, item. JobTitle, item. City, item. Country); }     to read a record that can be conditional, we filter out country is UK: code is as follows:  var query = from C in File.ReadAllLines File Path)  let CustomerRecord = line. Split (', ') select New Customer () {Firstname = customerrecord[0], Lastname = customerrecord[1],  jobtitle = Customerr ECORD[2], city = customerrecord[3], Country = customerrecord[4]}  where c.country = "UK" Select C;     Another example:     code is as follows: "var query = from c" (from lines in File.ReadAllLines (FilePath) Let CustomerRecord = line. Split (', ') select New Customer () {Firstname = customerrecord[0], Lastname = customerrecord[1], JobTitle = customerrecord[ 2], city = customerrecord[3], Country = customerrecord[4]} where C.jobtitle.contains ("Sales") select C;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.