簡體   English   中英

在可枚舉的方法中引用可枚舉的源代碼?

[英]Reference the source enumerable inside a method on that enumerable?

有沒有辦法在同一個可枚舉的運行方法中引用可枚舉的源?

例如,此代碼重復原始的可枚舉范圍1-6:

IEnumerable<int> result = Enumerable.Range(1, 6)
    .Where(a => Enumerable.Range(1, 6).Count() % 2 == 0);

我想知道是否有更簡潔的方法來重復原始的可枚舉,例如:

IEnumerable<int> result = Enumerable.Range(1, 6)
    .Where(a => [source reference].Count() % 2 == 0);

是的,我知道以下是一個解決方案...但有沒有辦法直接引用內存中的可枚舉,如上所示?

IEnumerable<int> source = Enumerable.Range(1, 6);
IEnumerable<int> result = source.Where(a => source.Count() % 2 == 0);

我不是要尋找上面代碼行的具體答案; 它們只是展示我想知道的一個例子。

內置的IEnumerable擴展方法都不能做你想要的。 它們都接受僅對單個項目進行操作的lamba表達式,因此表達式無法訪問父容器。

沒有什么可以阻止你自己滾動,例如:

public static IEnumerable<T> WhereSource<T> ( this IEnumerable<T> source, Func<IEnumerable<T>, T, bool> predicate)
{
  foreach (var item in source)
  {
    if (predicate(source, item))
    {
      yield return item;    
    }
  }
}

就個人而言,我認為您的原始解決方案更清晰,更易於維護,並且比制定您自己的自定義擴展方法更好,但它肯定是可能的。

你的意思是?

IEnumerable<int> source = Enumerable.Range(1, 6); //{1,2,3,4,5,6}
IEnumerable<int> result = source.Where((a, i) => i % 2 == 0); //{1,3,5}
IEnumerable<int> result2 = source.Where(a => a % 2 == 0); //{2,4,6}

不,你不能,因為Enumerable.Range(1, 6))沒有名字。

你將如何稱呼一個沒有名字的實體。

您的第3個代碼段是您可以使用的唯一解決方案,因為它沒有可以引用的名稱。

但是你可以做到

int length = 6; // Here hard-coded but can be passed from a parameter.
IEnumerable<int> source = Enumerable.Range(1, Length);
IEnumerable<int> result = source.Where(a => length % 2 == 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM