0

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; } } 

7 Answers 7

6

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); 
Sign up to request clarification or add additional context in comments.

Comments

6

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"} }; 

4 Comments

This could also be a little bit shorter by implementing a constructor on ValuesRow in that case you can just use: new ValuesRow("Value1", "1")
this is a long way. you can use loop for it.
@Serkan It is your personal opinion.
every comment is a personal opinion I know. Thank you.
1

You could also initialize the list like this:

Values = new List<ValuesRow> { new ValuesRow { Name = "AA", ID = 0}, new ValuesRow { Name = "BB", ID = 0} }; 

Comments

1

You could use AddRange method or create new list from array.

Values.AddRange(values.Select((value, index) => new ValuesRow {Name = value, ID = index.ToString() })); 

1 Comment

Or just use the array as a constructor parameter.
0
List<ValuesRow> vR = new List<ValuesRow>(); foreach(string item in values) { vR.Add(new ValuesRow {item,"0"}); } 

Do you want to make like this?

Comments

0
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"})); 

Comments

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"} }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.