C#: Cleanest way to divide a string array into N instances N items long

后端 未结 8 1359
我寻月下人不归
我寻月下人不归 2020-12-23 10:40

I know how to do this in an ugly way, but am wondering if there is a more elegant and succinct method.

I have a string array of e-mail addresses. Assume the string

相关标签:
8条回答
  • 2020-12-23 11:17

    You want elegant and succinct, I'll give you elegant and succinct:

    var fifties = from index in Enumerable.Range(0, addresses.Length) 
                  group addresses[index] by index/50;
    foreach(var fifty in fifties)
        Send(string.Join(";", fifty.ToArray());
    

    Why mess around with all that awful looping code when you don't have to? You want to group things by fifties, then group them by fifties. That's what the group operator is for!

    UPDATE: commenter MoreCoffee asks how this works. Let's suppose we wanted to group by threes, because that's easier to type.

    var threes = from index in Enumerable.Range(0, addresses.Length) 
                  group addresses[index] by index/3;
    

    Let's suppose that there are nine addresses, indexed zero through eight

    What does this query mean?

    The Enumerable.Range is a range of nine numbers starting at zero, so 0, 1, 2, 3, 4, 5, 6, 7, 8.

    Range variable index takes on each of these values in turn.

    We then go over each corresponding addresses[index] and assign it to a group.

    What group do we assign it to? To group index/3. Integer arithmetic rounds towards zero in C#, so indexes 0, 1 and 2 become 0 when divided by 3. Indexes 3, 4, 5 become 1 when divided by 3. Indexes 6, 7, 8 become 2.

    So we assign addresses[0], addresses[1] and addresses[2] to group 0, addresses[3], addresses[4] and addresses[5] to group 1, and so on.

    The result of the query is a sequence of three groups, and each group is a sequence of three items.

    Does that make sense?

    Remember also that the result of the query expression is a query which represents this operation. It does not perform the operation until the foreach loop executes.

    0 讨论(0)
  • 2020-12-23 11:22

    Assuming you are using .NET 3.5 and C# 3, something like this should work nicely:

    string[] s = new string[] {"1", "2", "3", "4"....};
    
    for (int i = 0; i < s.Count(); i = i + 50)
    {
        string s = string.Join(";", s.Skip(i).Take(50).ToArray());
        DoSomething(s);
    }
    
    0 讨论(0)
提交回复
热议问题