Use LINQ to move item to top of list

前端 未结 11 1408
轻奢々
轻奢々 2020-12-02 12:00

Is there a way to move an item of say id=10 as the first item in a list using LINQ?

Item A - id =5
Item B - id = 10
Item C - id =12
Item D - id =1

In th

11条回答
  •  悲哀的现实
    2020-12-02 12:41

    Here is an extension method you might want to use. It moves the element(s) that match the given predicate to the top, preserving order.

    public static IEnumerable MoveToTop(IEnumerable list, Func func) {
        return list.Where(func)
                   .Concat(list.Where(item => !func(item)));
    }
    

    In terms of complexity, I think it would make two passes on the collection, making it O(n), like the Insert/Remove version, but better than Jon Skeet's OrderBy suggestion.

提交回复
热议问题