1

I have an array of string defined as follows:

string[] items = { "Item 1", "Item 2", "Item 3", "Item 4"};

Then I have a model defined as :

public class ItemModel {

        public int Id { get; set; }

        public string ItemName { get; set; }

        public bool IsItem { get; set; }
}

I have defined a list as :

var listItems = new List<ItemModel>();

I want to add the items from the array items to the list of object of listItems. I want to add the items to ItemName

3
  • while adding to List<ItemModel> whats the Id and IsItem for respective item? Commented Oct 16, 2018 at 6:42
  • You want to set ItemName by some logic? or just randomly? Commented Oct 16, 2018 at 6:44
  • 2
    Possible duplicate of Convert from List of string array to List of objects Commented Oct 16, 2018 at 6:44

3 Answers 3

6

This can be achieved using a very simple Linq:

listItems  = items.Select(i => new ItemModel { ItemName = i}).ToList();
Sign up to request clarification or add additional context in comments.

8 Comments

@JohnB is the question duplicate or the answer? ;)
@JohnB well then you should comment it on question
@AshkanMobayenKhiabani Its recommended not to answer duplicates though. You have to make people search a bit (or direct them to the correct answer by marking as duplicate)
@EpicKip you are absolutely right, but when I saw the question, I didn't search it, I knew the answer, so I answered.
|
2

You could either use Select as:

  var result = items.Select(i => new ItemModel {ItemName = i}).ToList()

Or:

foreach(var item in items)
{
    listItems.Add(new ItemModel{ItemName = item});
}

Comments

0

You can try this:

    listItems = items.Select(i => new ItemModel { Id = Array.IndexOf(items, i), ItemName = i, IsItem = true }).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.