jpavlov
jpavlov

Reputation: 2261

Linq: splitting a string length and storing the result using a list

I am new to Linq and am re-factoring some of my old code over to Linq. I have a small problem that I solved using the foreach loop that stores each 250 char's to a list. It would be good to rewrite this using linq, but it seems to not be working. Can someone shed a little light on this?

Code to be refactored:

        string comment = "This can be however long but needs to be broken down into 250 chars and stored in a list";
        char[] charList = comment.ToCharArray();
        int charCount = charList.Count() / 250;

        List<string> charCollection = new List<string>();
        string tempStr = string.Empty;

        foreach (char x in charList){
            if (tempStr.Count() != 250){
                tempStr = tempStr + x.ToString();
            }
            else {
                if (tempStr.Count() <= 250)  {
                    charCollection.Add(tempStr);
                    tempStr = "";
                }
            }

Not so good attempt with Linq:

IEnumerable<string> charCat = System.Linq.Enumerable.Where(comment, n => n.ToString().Length() => 250);

Upvotes: 1

Views: 265

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

Using LINQ:

List<string> chunks = 
    comment
        // for each character in the string, project a new item containing the 
        // character itself and its index in the string
        .Select((ch, idx) => new { Character = ch, Index = idx })
        // Group the characters by their "divisibility" by 250
        .GroupBy(
            item => item.Index / 250, 
            item => item.Character, 
            // Make the result of the GroupBy a string of the grouped characters
            (idx, grp) => new string(grp.ToArray()))
        .ToList();

See the documentation for .GroupBy and .Select for more information on those methods.

In general, I think the 101 LINQ samples on MSDN are a great resource for learning LINQ.

Upvotes: 3

Related Questions