List and Arrays
I have 5 Values to add to a list. How can I make it cleaner with fewer lines of codes?
String[] values= new String[] { "AA", "BB", "CC", "DD", "EE", "FF" };
Values= new List<ValuesRow>();
foreach (var item in values)
{
Values.Add(new ValuesRow
{
Name = item,
ID = 0
});
}
public class ValuesRow
{
public 开发者_开发问答String Name { get; set; }
public String ID { get; set; }
}
If the list doesn't exists as in your sample :
var names = new[] { "AA", "BB", "CC", "DD", "EE", "FF" };
var Values = names.Select(name => new ValuesRow { Name = name, ID = "0" }).ToList();
otherwise
var names = new[] { "AA", "BB", "CC", "DD", "EE", "FF" };
var newElements = names.Select(name => new ValuesRow { Name = name, ID = "0" });
Values.AddRange(newElements);
If you need to add only 5 records which are known at compile time with less code you can try this:
var Values = new List<ValuesRow>
{
new ValuesRow{Name="Value1", ID="1"}
new ValuesRow{Name="Value2", ID="2"}
new ValuesRow{Name="Value3", ID="3"}
new ValuesRow{Name="Value4", ID="4"}
new ValuesRow{Name="Value5", ID="5"}
};
You could also initialize the list like this:
Values = new List<ValuesRow> { new ValuesRow { Name = "AA", ID = 0},
new ValuesRow { Name = "BB", ID = 0}
};
You could use AddRange
method or create new list from array.
Values.AddRange(values.Select((value, index) => new ValuesRow {Name = value, ID = index.ToString() }));
List<ValuesRow> vR = new List<ValuesRow>();
foreach(string item in values)
{
vR.Add(new ValuesRow {item,"0"});
}
Do you want to make like this?
String[] values= new String[] { "AA", "BB", "CC", "DD", "EE", "FF" };
var Values = new List<ValuesRow>();
Values.AddRange(values.Select(v => new ValuesRow() {Name = v, ID = "0"}));
How about using an object initialiser, which works like this:
var values = new List<ValuesRow>
{
new ValuesRow {ID = "0", Name = "AA"},
new ValuesRow {ID = "0", Name = "BB"},
new ValuesRow {ID = "0", Name = "CC"},
new ValuesRow {ID = "0", Name = "DD"},
new ValuesRow {ID = "0", Name = "EE"},
new ValuesRow {ID = "0", Name = "FF"}
};
精彩评论