按元素划分子列表中的列表

时间:2013-06-11 14:09:32

标签: c# linq

我有一个字符串列表:

{"foo", "str1", "str2", ..., "bar", ..., "baz", ...}

我需要在"foo""bar""baz"之间获取字符串的子列表。

是否可以使用linq执行此操作?

修改
我需要一个方法,而不是两次查看列表。

3 个答案:

答案 0 :(得分:6)

您可以这样做来细化任何两个其他元素之间的所有元素:

var strings = new[] { "foo", "str1", "str2", ... "bar", ... "baz" };
var between = strings.SkipWhile(s => s != "foo").Skip(1)
                     .TakeWhile(s => s != "bar"); // "str1", "str2", ...

如果你想获得“foo”和“baz”之间的所有内容,除了“bar”,请使用此(假设订单为“foo”,“bar”,“baz”):

var strings = new[] { "foo", "str1", "str2", ... "bar", ... "baz" };
var between = strings.SkipWhile(s => s != "foo").Skip(1)
                     .TakeWhile(s => s != "baz")
                     .Where(s => s != "bar"); // "str1", "str2", ...

或者,如果您对使用具有副作用的Linq查询感到满意,可以通过某些“停止”字词对输入列表进行分区:

 var stops = new[] { "foo", "bar", "baz" };
 var strings = new[] { "foo", "str1", "str2", "bar", "str3", "baz" };
 var p = -1;
 var partitions = 
     from s in strings
     let i = Array.IndexOf(stops, s) 
     group s by p = i == -1 ? p : i into g
     where g.Key == 0 || g.Key == 1
     select g.Skip(1); // { "str1", "str2" }, { "str3" }

或稍高效(因为它在第三个停用词之后停止处理):

 var partitions = 
     (from s in strings
      let i = Array.IndexOf(stops, s) 
      group s by p = i == -1 ? p : i)
     .SkipWhile(g => g.Key < 0)
     .Take(2)
     .Select(g => g.Skip(1)); // { "str1", "str2" }, { "str3" }

现在,这个方法在边缘有点粗糙,当它涉及“foo”之前或“baz”之后的项目时,它有些繁琐,但是如果因为你只是在“foo”和“巴兹”,它应该适合你。它还有一个好处,即停用词的顺序不会影响结果。

答案 1 :(得分:4)

var idxFoo = list.IndexOf("foo");
var idxBar = list.IndexOf("bar");
var idxBaz = list.IndexOf("baz");

var subList1 = list.Skip(idxFoo).Take(idxBar - idxFoo);
var subList2 = list.Skip(idxBar).Take(idxBaz - idxBar);

答案 2 :(得分:0)

如果您只想通过大量数据列表进行一次迭代,可以执行以下操作:

List<string> longDataList = new List<string> { "foo", "str1", "str2", "str1", "str2", "str1", "str2", "bar", "str1", "str2", "str1", "str2", "str1", "str2", "baz", "str1", "str2", "str1", "str2", "str1", "str2" };
List<string> splitters = new List<string> { "foo", "bar", "baz" };
Dictionary<string, List<string>> resultDict = new Dictionary<string, List<string>>();
List<string> currentList = null;
longDataList.ForEach(s =>
    {
       if (splitters.Contains(s))
          {
            if (resultDict.ContainsKey(s))
                currentList = resultDict[s];
             else
                {
                 currentList = new List<string>();
                  resultDict.Add(s, currentList);
                }
           }
        else
           currentList.Add(s);
     });

至少使用一点linq,但这个技巧只能在你的大量数据列表中迭代一次。