0

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 ;)

5 Answers 5

3

Yes, you can do it with LINQ:

var cats = (from sub in Subs
            select new Category
            {
                Name = sub
            }).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Or, in method call syntax, subs.Select(sub => new Category { Name = sub }).ToList().
2

You can use the ConvertAll method of the List class:

Cat = Subs.ConvertAll(s => new Category { Name = s });

Comments

2

In case both lists exist, Zip should be used:

 var result = categories.Zip(subs, (cate, sub) =>
            {
                cate.Name = sub;
                return cate;
            });

Comments

1

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();

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.