using System;
using System.Linq;
public class Program
{
public static void Main()
{
string [] lines = new string[2];
lines[0] = "John, 12345, true";
lines[1] = "Miles, 45678, true";
var o = from x in lines
let eachLine = x.Split(',')
select new {
name = eachLine[0],
zip = Int32.Parse(eachLine[1]),
status = bool.Parse(eachLine[2])
};
foreach (var p in o) {
Console.WriteLine(p.name + " - " + p.zip + ", - " + p.status);
}
}
}
I always think a let
is always cleaner here. I don't think there is a nicer way other than the split
, looks ok to me.
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string [] lines = new string[2];
lines[0] = "John, 12345, true";
lines[1] = "Miles, 45678, true";
var o = from line in
(
from inner in lines
select inner.Split(',')
)
select new {
name = line[0],
zip = Int32.Parse(line[1]),
status = bool.Parse(line[2])
};
foreach (var p in o) {
Console.WriteLine(p.name + " - " + p.zip + ", - " + p.status);
}
}
}
Another way of doing it is with an inner select @Habib has show the 'fluent' way of doing this below, this is the query version, which I think makes it easier to see wat is going on.
Enjoy your journey into LINQ!
If you can get a copy of Jon Skeet's 'C# In Depth', the section on LINQ is absolutely brilliant. As is the rest of the book.