从列表中获取两个项目之间的项目

时间:2014-02-17 16:10:12

标签: c# .net linq

我有List<string>,如下面的代码所示。

我需要在{}之间收集数据我不知道应该如何处理,所以我们将不胜感激。

send 1,
wait 200,
loop 5 {,
send 2,
wait 200,
},
send 3,
loop 2 {,
send a,
wait 50,
}

4 个答案:

答案 0 :(得分:4)

你可以这样做:

var firstIndex = list.FindIndex(r=> r.Contains('{'));
var secondIndex = list.FindIndex(r=> r.Contains('}'));
var result = list.Skip(firstIndex + 1).Take(secondIndex - (firstIndex +1));

结果将是:

enter image description here

问题的第一个版本没有指定多个段,我想这是在宽限期内添加的。上述版本的答案适用于字符串的单个段。为了使它能够与多个段一起使用,可以使用循环,如:

List<string> matchedItems = new List<string>();
List<string> listToWorkOn = new List<string>(list);
while(listToWorkOn.Any())
{
    var firstIndex = listToWorkOn.FindIndex(r => r.Contains('{'));
    var secondIndex = listToWorkOn.FindIndex(r => r.Contains('}'));
    matchedItems.AddRange(listToWorkOn.Skip(firstIndex + 1).Take(secondIndex - (firstIndex + 1)));
    listToWorkOn = listToWorkOn.Skip(secondIndex + 1).ToList();
}

matchedItems会从列表中生成4项。

答案 1 :(得分:1)

你可以这样做:

int n = 0;
while (n < list.Count)
{
    List<string> everythingBetweenBraces = new List<string>();
    if (list[n].EndsWith("{");
    {
        n++;
        while (list[n] != "}");
        {
            everythingBetweenBraces.Add(list[n]);
            n++;
        }
        n++; // Don't forget to jump to the next line after }
    }

    ...
}

检查当前行是否以{结尾,如果是,则将所有内容添加到新列表中,直到在一行上找到}

答案 2 :(得分:1)

你可以试试这个:

var s = new List<string>
        {
            "send 1",
            "wait 200",
            "loop 5 {send 2 wait 200}",
            "send 3",
            "loop 2 { send a, wait 50 }"
        };

foreach (var element in s)
{
    if(element.Contains("{"))
    {
        var index = element.IndexOf("{")+1;
        var lastIndex = element.IndexOf("}") - index;
        var sub = element.Substring(index, lastIndex).Trim();
        Console.WriteLine(sub);
    }
}

答案 3 :(得分:1)

这是另一种方法:

var list = new List<string>
        {
            "send 1",
            "wait 200",
            "loop 5 {",
            "send 2",
            "wait 200",
            "}",
            "send 3",
            "loop 2 {",
            "send a",
            "wait 50",
            "}"
        };

var indexes = list.Select((x, index) =>
        {
            if (x.Contains('{') || x.Contains('}')) return index;
            return -1;
        }).Where(x => x != -1).ToList();
var ranges = new Dictionary<int, int>();
for (int i = 0; i < indexes.Count; i += 2)
{
      ranges.Add(indexes[i],indexes[i+1]);
}
var resultList = list.Where((item, index) => 
                            ranges.Any(r => index > r.Key && index < r.Value))
                     .ToList();

输出:

enter image description here