开发者

Instantiate 2D Array with a LINQ Query

I am new to C#, so need your help.

I have a file that has a lot of lines and 3 tab delimited fields. I want to read each line, extract the fields from the line开发者_如何学C, and push the 3 extracted values into an object. In the end, I should get an array of objects. The length of the array should be equal to the number of lines in the file. And all the information in the file should get be contained in the objects.

Eg File

abcd pqrs mnop
asdf asdf asdf
poiu poiu poiu 
xcvx xcvb rtew
: : : :
: : : :
: : : :

This is what I could come up with:


Class Definition

Class MyClass
{
   string field1;
   string field2;
   string field3;
}

Main

String[] Content = File.ReadAllLines("file.txt");

  var query = from line in Content
              let Parts = line.Split(Separators,StringSplitOptions.RemoveEmptyEntries)
                          select new MyClass
                                    {field1 = Parts[0],
                                     field2 = Parts[1],
                                     field3 = Parts[2],
                                     };

How to I get a List or IEnumerable of objects from this?


Your code already gives you an IEnumerable<MyClass> value (in the query variable).
If you want a list, you can call ToList() on it.


var query = (from line in Content 
          let Parts = line.Split(Separators,StringSplitOptions.RemoveEmptyEntries) 
                      select new MyClass 
                                {field1 = Parts[0], 
                                 field2 = Parts[1], 
                                 field3 = Parts[2], 
                                 }).ToList<MyClass>();

That's it.

query will now be a List<MyClass>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜