创建列表<customObject>从列表<string>创建[英] Create List<CustomObject> from List<string>

本文是小编为大家收集整理的关于创建列表<customObject>从列表<string>创建的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个自定义对象,例如以下饰物定义:

string Name {get;set;}
string EmailAddress{get;set;}

另外,我有一个单独的List<string>包含所有"名称"

我想填充List<CustomObject>,每个自定义对象都有从List<string> names分配的名称.

如何使用linq?

实现这一目标

推荐答案

var strList = new List<string>();
var coList = strList.Select(item => new CustomObject() {Name = item}).ToList();

其他推荐答案

尝试以下内容:

List<CustomObject> customObjectList = 
    (from item in stringList
    select new CustomObject { Name = item, EmailAddress = String.Empty }).ToList();

其他推荐答案

编辑:删除垃圾类声明

IList<string> names = new List<string> { "first name", "second name" };
IList<SampleObject> myObjects = 
    names.Select(x => new SampleObject { Name = x }).ToList();

本文地址:https://www.itbaoku.cn/post/1556970.html

问题描述

I have a CustomObject, say defined with following attibutes:

string Name {get;set;}
string EmailAddress{get;set;}

Also, I have a separate List<string> that contains all 'names'

I want to populate List<CustomObject> with each CustomObject having its name assigned from List<string> names.

How can I achive this using Linq?

推荐答案

var strList = new List<string>();
var coList = strList.Select(item => new CustomObject() {Name = item}).ToList();

其他推荐答案

Try the following:

List<CustomObject> customObjectList = 
    (from item in stringList
    select new CustomObject { Name = item, EmailAddress = String.Empty }).ToList();

其他推荐答案

EDIT: removed rubbish class declaration

IList<string> names = new List<string> { "first name", "second name" };
IList<SampleObject> myObjects = 
    names.Select(x => new SampleObject { Name = x }).ToList();