用于从另一个列表中删除项目的扩展方法

时间:2010-07-20 08:47:13

标签: c# .net extension-methods

我试图根据谓词Func过滤列表。我使用Func过滤完整列表并返回操作结果。然后,我需要确定哪些MachineActions出现在完整列表中,而不是过滤后的列表。

static void Main(string[] args)
{
    var allActions = new List<MachineAction>
                     {
                         new MachineAction
                             { Name = "A", Status = MachineActionStatus.Cancelled },
                         new MachineAction
                             { Name = "B", Status = MachineActionStatus.Error },
                         new MachineAction
                             { Name = "C", Status = MachineActionStatus.Waiting }
                         };

     var filteredActions = allActions.Where(FilterNotCompleted);
}

private readonly static Func<MachineAction, bool> FilterNotCompleted = action =>
                                         (action.Status == MachineActionStatus.Waiting ||
                                          action.Status == MachineActionStatus.Started);

public class MachineAction
{
    public MachineActionStatus Status { get; internal set; }
    public string Name { get; internal set; }
}

internal enum MachineActionStatus
{
    Waiting,
    Started,
    Success,
    Error,
    Cancelled
} ;

是否有一种扩展方法可以将完整列表与已过滤列表进行比较,并返回不在两者中的那些?

由于

3 个答案:

答案 0 :(得分:2)

查看Except扩展程序

答案 1 :(得分:0)

allActions.Where(item => !filteredActions.Contains(item))

但也许更好的做法

var filteredActions = allActions.Where(item => !FilterNotCompleted(item));

(注意func命令之前的!)

答案 2 :(得分:0)

allActions.Except(filteredActions )