LINQ - is SkipWhile broken?

前端 未结 5 603
醉话见心
醉话见心 2020-12-30 22:54

I\'m a bit surprised to find the results of the following code, where I simply want to remove all 3s from a sequence of ints:

var sequence = new [] { 1, 1, 2         


        
相关标签:
5条回答
  • 2020-12-30 22:55

    One solution you may find useful is using List "FindAll" function.

    List <int> aggregator = new List<int> { 1, 2, 3, 3, 3, 4 };
    List<int> result = aggregator.FindAll(b => b != 3);
    
    0 讨论(0)
  • 2020-12-30 22:56
    var result = sequence.Where(i => i != 3);
    
    0 讨论(0)
  • 2020-12-30 23:11

    The SkipWhile and TakeWhile operators skip or return elements from a sequence while a predicate function passes (returns True). The first element that doesn’t pass the predicate function ends the process of evaluation.

    //Bypasses elements in a sequence as long as a specified condition is true and returns the remaining elements.

    0 讨论(0)
  • 2020-12-30 23:19

    It's not broken. SkipWhile will only skip items in the beginning of the IEnumerable<T>. Once that condition isn't met it will happily take the rest of the elements. Other elements that later match it down the road won't be skipped.

    int[] sequence = { 3, 3, 1, 1, 2, 3 };
    var result = sequence.SkipWhile(i => i == 3); 
    // Result: 1, 1, 2, 3
    
    0 讨论(0)
  • 2020-12-30 23:19

    Ahmad already answered your question, but here's another option:

    var result = from i in sequence where i != 3 select i;
    
    0 讨论(0)
提交回复
热议问题