1

I have

class Item
{
    public string Id {get;set;}
}

and this code

public void(List<string> sd)        
{
    List<Item> newitems = new List<Item>();
    foreach(var item in sd)
    {
        newItems.Add(new Item { Id = item});
    }
}

If sd contains more than ten items I should create new object List<Item> and initialize it by values from 11 item.

How much better to do it?

mason
  • 31,774
  • 10
  • 77
  • 121
i545219
  • 93
  • 6

2 Answers2

1

It seems that you want to create lists of Item from a list of string, you can use Select() to create a list instead of foreach. Then, you just need to split the list into sublists:

var allItems = sd.Select(id => new Item { Id = id });
var subLists = Split(allItems);

You can use the Split() method in this answer:

public static List<List<object>> Split(List<object> source)
{
    return source
        .Select((x, i) => new { Index = i, Value = x })
        .GroupBy(x => x.Index / 10)
        .Select(x => x.Select(v => v.Value).ToList())
        .ToList();
}
Community
  • 1
  • 1
Ken Hung
  • 752
  • 5
  • 13
0

I'm a C++ programmer so forgive any bad syntax, but this is where you can use a reference to a currentList that varies as you create a new list each time one fills up, using an if condition within your foreach.

public void(List<string> sd)        
{
    // Create a list of lists to store your lists.
    List<List<Item>> lists;

    // We're going to use this variable to refer to our
    // current, not-yet-full list (less than 10 items).
    List<Item> currentList;

    // Create the first list you'll be adding items to,
    // and add it to our list of lists.
    currentList = new List<Item>();
    lists.Add(currentList);

    foreach(var item in sd)
    {
        currentList.Add(new Item { Id = item});

        if(currentList.Count() >= 10)
        {
            // This should look familiar from above :-)
            currentList = new List<Item>();
            lists.Add(currentList);
        }
    }
}

If I've got some syntax wrong, please feel free to edit and correct my answer.

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145