tondre3na
tondre3na

Reputation: 29

List<String> to List<Object> C#

I've googled and seen conversions to List<Object>. But I think my case is different. I have the following:

public class Entry
{
    [XmlText]
    public string DataLogEntry { get; set; }
}

and used like this:

public class EndLot
{
    [XmlElement("Entry")]
    public List<Entry> Items;
}

So if I have list of strings ie.

List<string> EndLotLines

How can I create an instance of EndLot with this list. Am trying to:

List<Entry> Items =  (List<Entry>)EndLotLines;       

Upvotes: 2

Views: 155

Answers (3)

devdigital
devdigital

Reputation: 34349

Try the following:

var endLot = new EndLot
{
   Items = EndLotLines.Select(e => new Entry { DataLogEntry = e }).ToList();
};

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124632

You would have to create new Entry instances from each string. Would it make sense to write this?

Entry e = (Entry)"whatever";

No. You can use:

Items = EndLotLines.Select(s => new Entry { DataLogEntry = s }).ToList();

Upvotes: 2

p.s.w.g
p.s.w.g

Reputation: 148980

Use Linq's Select method:

var items = EndLotLines.Select(s => new Entry { DataLogEntry = s }).ToList();

Upvotes: 8

Related Questions