Linq:拆分字符串长度并使用列表存储结果

时间:2014-08-12 14:55:22

标签: c# linq

我是Linq的新手,正在将我的一些旧代码重新分解为Linq。我有一个小问题,我使用foreach循环解决了将每个250个字符存储到列表中的问题。使用linq重写它会很好,但它似乎不起作用。有人可以对此有所了解吗?

要重构的代码:

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

对Linq不太好的尝试:

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

1 个答案:

答案 0 :(得分:3)

使用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();

有关这些方法的详情,请参阅.GroupBy.Select的文档。

一般来说,我认为101 LINQ samples on MSDN是学习LINQ的重要资源。