简体   繁体   中英

How to convert a list of string to a list of a class in C#?

I have a list of string like this :

public List<string> Subs { get; set; }

and I have a list<Category> Cat { get; set; } list<Category> Cat { get; set; } 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 ;)

Yes, you can do it with LINQ:

var cats = (from sub in Subs
            select new Category
            {
                Name = sub
            }).ToList();

您可以使用List类的ConvertAll方法:

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

In case both lists exist, Zip should be used:

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

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

您必须手动创建一个函数,否则程序将很难理解哪个属性应该与列表中的字符串相对应。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM