0

是否可以在不使用 C# 循环 (foreach; for; while; etc) 而仅使用 C# Linq 或 lambda 表达式的情况下解决以下问题?

问题:给定一个 Task 对象列表和一个已删除 TaskId 的列表。我希望仅使用不在已删除 TaskId 列表中的元素更新列表,并且对剩余的 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;}

}

先感谢您。

4

2 回答 2

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
于 2013-04-17T14:28:38.233 回答
0
List<Task> tasksList = new List<Task>();
List<int> tasksIds = new List<int>();
List<Task> resultList = tasksList.FindAll(task => !taskIds.Contains(task.TaskId));
于 2013-04-17T14:28:50.323 回答