LINQ:选择对象不包含列表中的项目的位置

时间:2011-04-12 19:04:04

标签: c# linq

我在这里努力学习LINQ语法...我想在这里把它扔掉。我无法在其他任何地方找到我正在寻找的东西。

好吧,说我有这个:

public class Bar
{
   public int BarId { get; set; }
}

public class Foo
{
   public List<Bar> BarList { get; set; }
}

List<Foo> fooBunch = GetABunchOfFoos(); //let's just assume I'm getting more than one
List<Foo> fooSelect = new List<Foo>;
List<Bar> filterBars = GetAFewBars(); //assume I'm getting like 2 or 3

fooSelect = (from f in fooBunch
             where !(from b in f.BarList select b.BarId).Contains(ITEM FROM filterBars.BarId)
             select f).ToList();

所以,长话短说我想用LINQ根据另一个列表中的对象过滤掉我的对象列表。我希望这是有道理的。我想我只是迷失在Contains部分...我不知道怎么写。

4 个答案:

答案 0 :(得分:110)

一般情况下,您正在寻找“除外”扩展名。

var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);

在此示例中,GenerateRegectStatuses()应该是您要拒绝的状态列表(或者根据您的示例更具体的术语,List<int> ID

答案 1 :(得分:67)

将其转储到您不想要的ID的更具体的集合

var notTheseBarIds = filterBars.Select(fb => fb.BarId);

然后试试这个:

fooSelect = (from f in fooBunch
             where !notTheseBarIds.Contains(f.BarId)
             select f).ToList();

或者这个:

fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();

答案 2 :(得分:5)

我没有试过这个,所以我不保证任何东西,不过

foreach Bar f in filterBars
{
     search(f)
}
Foo search(Bar b)
{
    fooSelect = (from f in fooBunch
                 where !(from b in f.BarList select b.BarId).Contains(b.ID)
                 select f).ToList();

    return fooSelect;
}

答案 3 :(得分:4)

试试这个简单的LINQ:

//For a file list/array
var files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);

//simply use Where ! x.Contains
var notContain = files.Where(x => ! x.Contains(@"\$RECYCLE.BIN\")).ToList();

//Or use Except()
var containing = files.Where(x => x.Contains(@"\$RECYCLE.BIN\")).ToList();
    notContain = files.Except(containing).ToList();