Reputation: 134
I have a CSV
list of values which I am converting into a User
object.
I have done this via a foreach loop but wonder if there's a way of doing this via LINQ
in a more efficient manner?
I've tried a combination of using Select
and Where
but cannot seem to find a method specific to my case.
User.cs:
public class User
{
public string FirstName {get; set;}
public string LastName { get; set; }
public string Password { get; set; }
}
Current way of doing it:
var lines = File.ReadAllLines(filepath).Select(x => x.Split(';'));
var users = new List<User>();
foreach (var line in lines)
{
var user = new User
{
FirstName = line[0],
LastName = line[1],
Password = line[2]
};
users.Append(user);
}
Upvotes: 0
Views: 704
Reputation: 2367
What about :
var users = lines.Select(line=>new User
{
FirstName = line[0],
LastName = line[1],
Password = line[2]
}).ToList();
The last ToList is optional whether you want to collect immediatly or not.
You can even in one step like:
var users = File.ReadAllLines(filepath).Select(x=>
{
var line = x.Split(';');
return new User
{
FirstName = line[0],
LastName = line[1],
Password = line[2]
};
}).ToList();
Edit: To clarify I decompose :
var users = File.ReadAllLines("filepath").Select(BuildFromLine).ToList();
The select takes as a parameter a Function with a string as input and whatever as output (here a user). Then I have a function to build my users. In the above notation I transformed the function in an anonymous lambda. Note that for clarity I kept the name x for the parameter of the function but in the real world I would have renamed it to reflect what it really is (x becomes line and line becomes tokens).
public static User BuildFromLine(string x)
{
var line = x.Split(';');
return new User
{
FirstName = line[0],
LastName = line[1],
Password = line[2]
};
}
Upvotes: 7
Reputation: 37460
You could to it entirely with LINQ:
var users = File.ReadAllLines(path)
.Select(line => line.Split(';'))
.Select(splitLine => new User { FirstName = splitLine[0], LastName = splitLine[1], Password = splitLine[2] })
.ToArray();
Upvotes: 0