ASP.NET Add items to a list

时间:2016-10-20 18:35:28

标签: c# asp.net

I am trying to add items to a list:

List<string> newList = new List<string>();
foreach (var x in dbTimeSlots.Data)
{
    newList.Add(x.id.ToString());
    newList.Add(x.timeSlot + " - " + x.dateSlot);
}

However my list returns 80 items when I only have 40, this is happening because the id will be one item and the the time and date will be another, I need them as one row, but each row should have an id object, and date and time object. I hope this makes sense, please help!!!!

3 个答案:

答案 0 :(得分:7)

I need them as one row, but each row should have an id object, and date and time object

Then you don't need a List<string> but a List<CustomObject> where CustomObject is an object with the properties you specified. Then for each item in dbTimeSlots.Data you should create such an object and then add this to your list.

public class CustomObject
{
    public string Id { get; set; }
    public string TimeSlot { get; set; }
    public string DateSlot { get; set; }
}

Then with the foreach loop:

var newList = new List<CustomObject>();
foreach (var x in dbTimeSlots.Data)
{
    var customObject = new CustomObject
    {
        Id = x.id.ToString(),
        TimeSlot = x.timeSlot,
        DateSlot = x.dateSlot
    };
    newList.Add(customObject);
}

Or with LINQ:

var newList = dbTimeSlots.Data.Select(x => new CustomObject
{
    Id = x.id.ToString(),
    TimeSlot = x.timeSlot,
    DateSlot = x.dateSlot
}).ToList();

答案 1 :(得分:2)

Create a model to store the type you want or use an anonymous type.

var newList = dbTimeSlots.Data.Select(x => new 
    { 
         id = x.id, 
         timeDateSlot = x.timeSlot + " - " + x.dateSlot 
    }).ToList();

答案 2 :(得分:1)

Another possible option that may work for you is to use a Dictionary instead of a List.

var myDictionary = new Dictionary<string, string>();
foreach (var x in dbTimeSlots.Data)
{
    myDictionary.Add(x.id.ToString(), x.timeSlot + " - " + x.dateSlot);
}