开发者

c# More elegant way to assign array to a list?

I have this:

// Load changelog types
ChangeLogType[] Types = ChangeLogFunctions.GetAllChangelogTypes();
foreach(ChangeLogType Rec in Types){
    ListItem N = new ListItem();
    N.Text = Rec.Type;
    N.Value = Rec.ID.ToString();
    LstChangeLogType.Items.Add(N);
}

It calls a function that returns an array of ChangeLogTypes, and 开发者_运维问答then adds each one into a list control. Is there a more elegant way of doing this? I feel I'm repeating code each time I do this or something similar.


Yup, LINQ to Objects is your friend:

var changeLogTypes = ChangeLogFunctions.GetAllChangelogTypes()
                                       .Select(x => new ListItem { 
                                                      Text = x.Type,
                                                      Value = x.ID.ToString() })
                                       .ToList();

The Select part is projecting each ChangeLogType to a ListItem, and ToList() converts the resulting sequence into a List<ListItem>.

This is assuming you really wanted a new list with all these entries. If you need to add the results to an existing list, you'd do that without the ToList call, but calling AddRange on an existing list with the result of the Select call.

It's well worth learning more about LINQ in general and LINQ to Objects in particular - it can make all kinds of things like this much simpler.


var range = Types.Select(rec => 
       new ListItem { Text = rec.Type, Value = rec.ID.ToString() });

LstChangeLogType.AddRange(range);


Linq?

LstChangeLogType.Items = Types.Select(x => new ListItem() 
                     { Text = x.Type, Value = x.ID.ToString() }).ToList();


using System.Linq;

var items = Types
  .Select (rec => ListItem
    {
      Text = Rec.Type;
      Value = Rec.ID.ToString();
    }

LstChangeLogType.Items.AddRange(items);


Using some LINQ extension methods:

LstChangeLogType.AddItems.AddRange(
    Types.Select(t => 
        new ListItem() { Text = t.Type, Value = t.ID.ToString() }).ToArray());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜