Reputation: 1152
I have a list of string
like this :
public List<string> Subs { get; set; }
and I have a list<Category> Cat { get; set; }
of this class :
public class Category
{
public int ID { get; set; }
public string Name { get; set; }
public int SubCat_ID { get; set; }
}
I just need to put all of the values in the list<string> Subs
into the List<Category> Cat
. and of course each string in the list<string>
should be placed in each Name parameter of List<Category>
.
So how is it done ? Is there any convert method which does the thing? how does it work ?
Thanks in advance ;)
Upvotes: 0
Views: 212
Reputation: 75306
In case both lists exist, Zip should be used:
var result = categories.Zip(subs, (cate, sub) =>
{
cate.Name = sub;
return cate;
});
Upvotes: 2
Reputation: 57172
You can use the ConvertAll
method of the List
class:
Cat = Subs.ConvertAll(s => new Category { Name = s });
Upvotes: 2
Reputation: 8005
Use the "Select" enumerable extension method:
http://msdn.microsoft.com/en-us/library/bb548891.aspx
followed by a "ToList()" like this:
var newList = Subs.Select(name => new Category { Name = name}).ToList();
Upvotes: 1
Reputation: 415
You have to make a function manually, otherwise it would be very hard for the program to understand what property should correspond to the string in the list.
Upvotes: 0
Reputation: 1252
Yes, you can do it with LINQ:
var cats = (from sub in Subs
select new Category
{
Name = sub
}).ToList();
Upvotes: 3