2

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, 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?

Deepak
  • 731
  • 2
  • 9
  • 14

2 Answers2

4

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Hi, If you can write the code for me, I'll really be grateful. What I'm not able to get is how I should execute the LINQ Query. Using a foreach? – Deepak Nov 03 '10 at 12:54
  • @Deepak: The LINQ query produces an `IEnumerable` that can be treated like any other collection. You can use a normal `foreach` loop. – SLaks Nov 03 '10 at 12:57
  • 1
    foreach(var x in query){//x.field1,x.field2...all accessible} – Gage Nov 03 '10 at 12:58
  • Also try to avoid arrays, lists are the new arrays for C#. Check out http://stackoverflow.com/questions/2975426/which-is-better-to-use-array-or-list – Gage Nov 03 '10 at 13:00
1
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>

Ryan Bennett
  • 3,404
  • 19
  • 32