2

我有以下代码:

public class MyObject {
  public string Name { get; set; }

  public MyObject(string name) {
    Name = name;
  }  
}

// caller method somewhere
public void myMethod() {
  List<MyObject> myObjects = new List<MyObject>();
  myObjects.Add(new MyObject("Jim"));
  myObjects.Add(new MyObject("David"));
  myObjects.Add(new MyObject("Richard"));
  myObjects.Add(new MyObject("Steve"));

  string[] namesToExclude = new string[] { "Jim", "Steve" };
  List<string> strings = myObjects.Select(m => m.Name).Except(namesToExclude).ToList();
  // replace the above line to result in List<MyObject> with 2 items (David, Richard)
}

我想让最后一行正常工作,这样我就可以将列表作为 aList<MyObject>而不是作为List<string>.

4

5 回答 5

7

试试这个:

 var objects = 
      myObjects.Where(m => !namesToExclude.Contains(m.Name)).ToList();
于 2012-10-24T19:30:12.583 回答
3

您可以使用原始列表并将Except结果join

var allowedObjNames = myObjects.Select(o => o.Name).Except(namesToExclude);
var allowedObject = from o in myObjects join a in allowedObjNames 
                    on o.Name equals a
                    select o;
var allowedObjList = allowedObject.ToList();
于 2012-10-24T19:30:50.380 回答
2

这可能有点错误,因为我习惯于更多地使用 VB.NET,但类似......

(from m in myObjects where !namesToExclude.Contains(m.Name)).ToList()
于 2012-10-24T19:30:17.097 回答
2
var objs = myObjects.Where(m => !namesToExclude.Contains(m.Name)).ToList();
于 2012-10-24T19:30:49.270 回答
2

将最后一行替换为 -

List<MyObject> objects = myObjects.Where(o =>
                           !namesToExclude.Contains(o.Name)).ToList();
于 2012-10-24T19:32:58.750 回答