1

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?

3 Answers 3

4
var strList = new List<string>();
var coList = strList.Select(item => new CustomObject() {Name = item}).ToList();
Sign up to request clarification or add additional context in comments.

Comments

3

Try the following:

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

1 Comment

+1 for omitting the () and spacing the object initializer properly. -1 for using query-style where it's absolutely not needed and further perverting it by wrapping it in parenthesis to use .ToList.
2

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

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.