LINQ: Convert String array to List of objects of custom class

Suppose we have a user class
public class User
 public string Name { get; set; }
and we have the usernames in a string array as shown below
string[] names = new string[5] {"John", "David", "Robert", "Paul", "Mary" };
if we want to convert it as list of User class objects, the general method for this is
List usersList =new List();
foreach(var name in names)
usersList.Add(new User(){
Using LINQ, we can achive the same with a single line
List usersList = names.Select(x => new User() { Name = x } ).ToList();
Happy Coding 😊 !!


    Blogger Comment
    Facebook Comment


Post a Comment