亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將兩個序列與其元素交錯連接

將兩個序列與其元素交錯連接

C#
蝴蝶不菲 2022-12-24 12:47:53
我想連接兩個序列的元素,生成一個包含原始兩個序列的所有元素的單個序列,但它們的元素交錯。ConcatLINQ 方法可以進行連接但沒有交錯,所以我需要一些特別的東西。交錯規則如下:對于每對元素,selector應該調用一個函數,并且選擇的元素應該是第一個或第二個,具體取決于boolean函數的結果(true:第一個,false:第二個)這是我想要實現的實際示例:var sequence1 = new int[] { 1, 2, 3 };var sequence2 = new int[] { 11, 12, 13 };var result = sequence1.ConcatInterleaved(sequence2, (a, b) => (a + b) % 3 == 0);Console.WriteLine(String.Join("\r\n", result));預期輸出:1  // Because (1 + 11) % 3 == 0, the first is selected11 // Because (2 + 11) % 3 != 0, the second is selected12 // Because (2 + 12) % 3 != 0, the second is selected2  // Because (2 + 13) % 3 == 0, the first is selected13 // Because (3 + 13) % 3 != 0, the second is selected3  // Because sequence2 has no more elements, the next element of sequence1 is selected我想要一個 LINQ 解決方案,以便本著內置 LINQ 方法的精神可以推遲實際的串聯。這是我目前的嘗試:public static IEnumerable<TSource> ConcatInterleaved<TSource>(    this IEnumerable<TSource> source,    IEnumerable<TSource> other,    Func<TSource, TSource, bool> selector){    // What to do?}更新:我更改了示例,因此它看起來不像是簡單的交替交錯。關于該selector函數的說明:該函數不適用于兩個序列的預選對,就像它在Zip方法中發生的那樣。這些對不是預定義的。每次選擇后都會形成一個新對,其中包含先前選擇的拒絕元素和先前選擇的序列中的新元素。例如對于選擇器(a, b) => truetheConcatInterleaved變得等效于Concat:返回 sequence1 的所有元素,然后是 sequence2 的所有元素。另一個例子:使用選擇器(a, b) => false返回 sequence2 的所有元素,然后是 sequence1 的所有元素。
查看完整描述

1 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

public static IEnumerable<T> Weave(

  this IEnumerable<T> left,

  IEnumerable<T> right,

  Func<T, T, bool> chooser)

{

  using(var leftEnum = left.GetEnumerator())

  using(var rightEnum = right.GetEnumerator())

  {

    bool moreLeft = leftEnum.MoveNext;

    bool moreRight = rightEnum.MoveNext;

    while(moreLeft && moreRight)

    {

      if (chooser(leftEnum.Current, rightEnum.Current))

      {

        yield return leftEnum.Current;

        moreLeft = leftEnum.MoveNext();

      }

      else

      {

        yield return rightEnum.Current;

        moreRight = rightEnum.MoveNext();

      } 

    }

    // yield the buffered item, if any

    if (moreLeft) yield return leftEnum.Current;

    if (moreRight) yield return rightEnum.Current;


    // yield any leftover elements

    while (leftEnum.MoveNext()) yield return leftEnum.Current;

    while (rightEnum.MoveNext()) yield return rightEnum.Current;

  }

}


查看完整回答
反對 回復 2022-12-24
  • 1 回答
  • 0 關注
  • 103 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號