如何用LINQ切断字符串

时间:2012-03-22 09:05:50

标签: c# .net string linq

我有一个需要切碎的字符串。我想在LINQ中这样做。 该字符串最多可包含32个字母。 我想在字典中收集这些部分。

The 1st part needs to have the first 4 letters. 
The 2nd part needs to have the first 5 letters. 
The 3rd part needs to have the first 6 letters. 
etc.

字典的关键只是一个计数器。我不知道弦的长度,分钟。长度是4。 我如何在LINQ中创建这个?

3 个答案:

答案 0 :(得分:4)

我不知道我是否理解你想做什么,但也许你正在寻找这样的事情:

using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var s = "This is a simple string";
            var dic = Enumerable.Range(4, s.Length-3)
                                .Select((m, i) => new { Key = i, Value = s.Substring(0, m) })
                                .ToDictionary(a=>a.Key,a=>a.Value);
        }
    }
}

答案 1 :(得分:1)

你可以把它作为一个扩展名:

public static Dictionary<int, String> Chop(this string str, int minLength)
{
    if (str == null) throw new ArgumentException("str");
    if (str.Length < minLength) throw new ArgumentException("Length of string less than minLength", "minLength");
    var dict = str.TakeWhile((c, index) => index <= str.Length - minLength)
        .Select((c, index) => new { 
            Index = index, 
            Value = str.Substring(0, minLength + index) 
        }).ToDictionary(obj => obj.Index, obj => obj.Value);

    return dict;
}

以这种方式调用它:

Dictionary<int, String> = "Insert sample string here".Chop(4);

答案 2 :(得分:0)

string word = "abcdefghijklmnopqrstuvwz";

var dict = new Dictionary<int, string>();
for(int i = 0; i < 28;i++)
{
   dict[i] = new string(word.Take(i + 4).ToArray());
}