删除并重新排序列表元素

时间:2013-04-17 14:16:51

标签: c# linq linq-to-objects

是否可以使用C#循环(foreach; for; while; etc)解决以下问题 WITHOUT ,但只能解决C#Linq或lambda表达式?

问题: 给定Task对象列表和已删除TaskIds列表。我希望该列表仅使用已删除的TaskIds列表中 NOT 的元素进行更新,其余的Task元素也会重新排序。

详细说明:

(1*) Given a list of Task objects:

TaskId  Group   Name    Order


281        1    "abc"   1  
726        1    "dre"   2  // note: will be removed  
9891       1    "euf"   3  // note: will be removed  
87         1    "wop"   4  
932        1    "hjd"   5  

102        2    "fhl"   1  // note: will be removed  
44         2    "bgg"   2  
30         2    "qds"   3  
293        2    "djf"   4  // note: will be removed  
389        2    "hkd"   5  

12         3    "hjf"   1  
900        3    "xdf"   2  // note: will be removed  


(2*) Given a list of removed TaskIds:  
TaskId  
726  
9891  
102  
293  
900  

现在,在删除基于列表(2 *)的列表(1 *)之后,我希望列表(1 *)看起来像(注意:其余元素的订单也会更新):

列表(1 *)已更新:

TaskId  Group   Name    Order  

281        1    "abc"   1  
87         1    "wop"   2  // note: new order  
932        1    "hjd"   3  // note: new order  

44         2    "bgg"   1  // note: new order  
30         2    "qds"   2  // note: new order  
389        2    "hkd"   3  // note: new order  

12         3    "hjf"   1  // note: order is kept unchanged.    

Task类的定义如下:

 public class Task {
      public int TaskId { get;set; }
      public int Group { get; set;}
      public string Name { get; set; }
      public int Order { get; set;}

}

提前谢谢。

2 个答案:

答案 0 :(得分:6)

var tasks = new[]{
        new Task{TaskId = 281, Group = 1, Name = "abc", Order =1},
        new Task{TaskId = 726 , Group = 1, Name = "dre", Order =2},
        new Task{TaskId = 9891, Group = 1, Name = "euf", Order =3},
        new Task{TaskId = 102, Group = 2, Name = "wop", Order =1},
        new Task{TaskId = 44, Group = 2, Name = "wop", Order =2},
        new Task{TaskId = 30, Group = 2, Name = "wop", Order =3},
        new Task{TaskId = 293, Group = 2, Name = "wop", Order =4},
        new Task{TaskId = 295, Group = 3, Name = "was", Order =1},
};

int[] itemsToRemove = {726, 102, 293};

tasks.Where(task => !itemsToRemove.Contains(task.TaskId))
     .GroupBy(task => task.Group)
     .SelectMany(grp => grp.Select((task, grpIndex) => 
                                   { task.Order = grpIndex + 1; return task; }));

这将返回:

TaskId Group   Name Order
281    1       abc  1 
9891   1       euf  2 
44     2       wop  1  
30     2       wop  2 
295    3       was  1

答案 1 :(得分:0)

List<Task> tasksList = new List<Task>();
List<int> tasksIds = new List<int>();
List<Task> resultList = tasksList.FindAll(task => !taskIds.Contains(task.TaskId));