如何使用LINQ读取文本文件并将其转换为C#类对象属性 [英] How to read text file using LINQ and covert it into C# class object properties

查看:102
本文介绍了如何使用LINQ读取文本文件并将其转换为C#类对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个文本文件,需要从第4行读到结束(第100行)并将其转换为C#Class CountryList(属性)。

我需要从行号4到结束,分割逗号(,)分隔值并分配给C#类CountryList(属性)



示例文本文件: -

Hi,
I have a text file and need to read from line number 4 to end(line no 100) and convert it into C# Class CountryList(Properties).
I need to Make from Line number 4 to end, split comma(,) separate values and assign to C# Class CountryList(Properties)

Sample Text File :-

   Country : INDIA    // Line No : 1
Currency : INR

1,RRRR
2,EEEE
3,WWWW
4,WWAA
5,FDSDF
6,WERWER
7,SFSDF
8,FDAF
9,DFDSFA
..... SO ON





我尝试了什么: < br $> b $ b

C#代码: -



What I have tried:

C# Code:-

public class CountryList
{
    public string ID { get; set; }
    public string NAME { get; set; }
}

string strReadFile = @"D:\Country.txt";
    int startLine = 4;
    int lineCount = 100;
    var fileLines = File.ReadAllLines(strReadFile)
                        .Skip((startLine))
                        .Take(lineCount)
                        .ToList();

推荐答案

试试这个



try this

var fileLines = File.ReadAllLines(strReadFile).Skip((startLine)).Take(lineCount).ToList();
       List<CountryList> lst = new List<CountryList>();
       foreach (string line in fileLines)
       {
           string[] temp = line.Split(',');
           if (temp.Length >= 2)
           {
               CountryList country = new CountryList();
               country.ID = temp[0].Trim();
               country.NAME = temp[1].Trim();
               lst.Add(country);
           }
       }


关于逗号分隔文件的快速简便解决方案的常见问题之一是最终你将遇到具有双引号文本限定符的csv。所以为此,我总是推荐TextFieldParser。



One of the common problems with "quick and easy" solutions with regards to comma delimited files is the fact that eventually you will run across a csv that has double quote text qualifiers. So for this end, I always recommend TextFieldParser.

using Microsoft.VisualBasic.FileIO;

void Main()
{
	string strReadFile = @"D:\Country.txt";
	List<CountryList> lst = ParseCountryList(strReadFile, ",", true);
}

class CountryList
{
	public string ID { get; set; }
	public string NAME { get; set; }
}

static List<CountryList> ParseCountryList(string FileName, string Delimiter, bool IsQualified)
{
	var result = new List<CountryList>();
	using (var tfp = new TextFieldParser(FileName) {
		Delimiters = new string[] { Delimiter },
		HasFieldsEnclosedInQuotes = IsQualified
	})
	{
		while (!tfp.EndOfData)
		{
			var fields = tfp.ReadFields();
			if (fields.Length >= 2)
			{
				var cl = new CountryList
				{
					ID = fields[0].Trim(),
					NAME = fields[1].Trim()
				};
				result.Add(cl);
			}
		}
	}
	return result;
}


AFell提出了有关CSV文件潜在问题的好处。

我现在要假设你知道文件格式永远不会有引用的ID值,包括逗号。

至少这应该为你提供一个更复杂的起点,如果必要的话。 br />
AFell raises good points about CSV file potential issues.
I'm going to assume that for now you know that the file format never has an ID value that's quoted including a comma.
At a minimum this should give you a starting point for something more sophisticated if necessary.
// You don't need to read all of the lines into an array, just read 'em as you go
char [] delimiters = new char[] { ',' };
var fileLines = File.ReadLines(strReadFile)
                    .Skip(startLine)
                    // .Take(..) is necessary ONLY if you DON'T want to read to the end
                    // in your question you said "from Line number 4 to end"
                    // .Take(lineCount)
                    .Select(line => {
                       string[] ss = line.Split(delimiters, 2);
                       return (ss.Length == 2)
                              ? new CountryList() { ID = ss[0], NAME = ss[1] }
                              : null;              // null for ill-formatted line
                     })
                    .Where(x => x != null)      // filter to good lines
                    .ToList();



(我没有测试这......可能有一两个错字......)


(I didn't test this... There may be a typo or two...)


这篇关于如何使用LINQ读取文本文件并将其转换为C#类对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆