簡體   English   中英

如何在有條件的一列中使用LINQ select

[英]How to use LINQ select in one column with condition

像這樣的數據表...

Date       Count
20160101   100
20160102   103
20160103   108
20160104   102
20160105   104
20160106   106
20160107   108

我想select if => someday.Count > someday[-3].Count

結果= 3行如下:

20160104,因為102> 100
20160105,因為104> 103
20160107,因為108> 102

請告訴我如何使用LINQ?
非常感謝

您可以使用將Func<TSource, int, bool> predicate作為輸入的Where重載。 此委托的第二個輸入是當前元素的索引。 因此,這意味着您的lambda表達式必須接受兩個輸入,第一個輸入將是您元素的類型,而另一個將是Int32 Where方法將自動計算當前元素的索引。

var result = myColl.Where((x, index) => index >= 3 && x.Count > myColl.ElementAt(index - 3).Count);

然后,您可以使用所需的方法,如Select()ToList()等。

PS:我假設對象的名稱是myColl

另外:

我總是喜歡向開發人員介紹http://referencesource.microsoft.com/ 您可以輕松地找到所有方法的實現以及有關C#源代碼的所有信息。 如果您有興趣,這里是重載Where方法的源代碼。

    public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate) {
        if (source == null) throw Error.ArgumentNull("source");
        if (predicate == null) throw Error.ArgumentNull("predicate");
        return WhereIterator<TSource>(source, predicate);
    }

如您所見,它將返回WhereIterator並將自動計算當前項目的索引並將其發送到您的方法:

static IEnumerable<TSource> WhereIterator<TSource>(IEnumerable<TSource> source, Func<TSource, int, bool> predicate) {
    int index = -1;
    foreach (TSource element in source) {
        checked { index++; }
        if (predicate(element, index)) yield return element;
    }
}

一種方法是這樣做。

int index = 0;
var a = from i in someday
        let indexNow = index++
        where indexNow >= 3
        let j = someday[indexNow - 3]
        where i.Count > j.Count
        select i;

在創建臨時變量j之前,需要獲取三個步驟,然后將其與當前元素進行比較以檢查其是否滿足特定條件。 如果是,則選擇它

使用索引的Where -overload,如下所示:

var result = myDates.Where((x, index) => index >= 3 && x > myDates.ElementAt(x - 3).Count);

這將從您的集合中選擇所有元素,這些元素的數量要比三天前的元素要多。

盡管其他答案中描述的索引技術將起作用,但如果源序列不是基於列表的,則它們將效率低下,在這種情況下ElementAt將導致O(N ^ 2)時間復雜度運算。

僅具有O(N)時間復雜度(如果源序列本身不包含繁重的操作)的一種可能更好的方法是使用SkipZip的組合,例如

var result = myDates
    .Skip(3)
    .Zip(myDates, (current, compare) => current.Count > compare.Count ? current : null)
    .Where(item => item != null);

暫無
暫無

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

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