LINQ在List <t>元素列表中启动和停止段

时间:2016-04-25 11:46:43

标签: c# linq sequence morelinq

给出一个类的对象列表(List<Type1>

item1.isbool = true, beat = 1
item2.isbool = true, beat = 1.333
item3.isbool = true, beat = 1.666
item4.isbool = false, beat = 2
item5.isbool = false, beat = 3
item6.isbool = false, beat = 4
item7.isbool = false, beat = 5
item8.isbool = true, beat = 5.333
item9.isbool = true, beat = 5.666

我想在连音符组(可变大小)中获取起始值和停止值以添加到第二个类的列表(List<Type2>.Add()

item1.tuplet = start
item3.tuplet = stop
item8.tuplet = start
item9.tuplet = stop

元素的顺序很重要。 MoreLinq作为一个选项,但不确定我需要执行哪些类型的操作来获取这些值。它可以是分区或某种GroupBy,但这似乎不起作用。

我最终需要的结果将是

List2.Add(new Object() {Tuplet = TupletType.Start});
List2.Add(new Object() {Tuplet = TupletType.None});
List2.Add(new Object() {Tuplet = TupletType.Stop});
List2.Add(new Object() {Tuplet = TupletType.None});
List2.Add(new Object() {Tuplet = TupletType.None});
List2.Add(new Object() {Tuplet = TupletType.None});
List2.Add(new Object() {Tuplet = TupletType.None});
List2.Add(new Object() {Tuplet = TupletType.Start});
List2.Add(new Object() {Tuplet = TupletType.Stop});

2 个答案:

答案 0 :(得分:2)

您可以使用扩展方法进行分组,然后您可以使用:

List<Type1> runs = ...

List<Type2> grouped = new List<Type2>();
grouped.AddRange(runs.GroupByRuns());

以下是扩展方法的可能解决方案:

public static class GroupType
{
    public static IEnumerable<Type2> GroupByRuns(this IEnumerable<Type1> sequence)
    {
        if (sequence.Count() == 0)
            yield break;

        List<bool> next_items = sequence.Select(s => s.isbool).ToList();
        next_items.Add(false);

        bool previous_item = false;
        int idx = 1;
        foreach (var item in sequence)
        {
            if (item.isbool)
            {
                if (previous_item == false)
                {
                    yield return new Type2 { Tuple = Type2.TupletType.Start };
                }
                else if (next_items.ElementAt(idx) == true)
                {
                    yield return new Type2 { Tuple = Type2.TupletType.None };
                }
                else
                {
                    yield return new Type2 { Tuple = Type2.TupletType.Stop };
                }
            }
            else
            {
                yield return new Type2 { Tuple = Type2.TupletType.None };
            }
            previous_item = item.isbool;
            idx++;
        }
    }
}

答案 1 :(得分:0)

这是一个for循环的例子。

Type1 start;
Type1 stop;

for (int i=0; i<list.Length; i++)
{
  if(start == null && list[i].isbool)
    start = item[i];
  if(start != null && (i+1 == list.Length) || !list[i+1].isbool)
  //no next item or next item is false? Found the stop.
  {
    stop = item[i];//Found a start & stop, add them to a list
    start = null;
  }
}