0

给定一个类的对象列表 ( 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});
4

2 回答 2

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++;
        }
    }
}
于 2016-04-25T12:56:28.540 回答
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;
  }
}
于 2016-04-25T12:24:19.377 回答