在linq';中使用Contains方法;s Where条款

本文关键字:方法 Contains 条款 Where linq | 更新日期: 2023-09-27 18:13:27

我的查询有问题。我有两节简单的课。比方说

public class A{
  public List<B> MyCollection{get; set;}
}
public class B{
 public string Id;
}
//I want to do something like that
var myB = new B{Id="1"};
context.A.Where( x=> x.MyCollection.Contains(myB)).ToList();

我该如何解决这个问题?我知道我可以做一些类似的事情

context.A.ToList().Where...

但这不是个好主意,尤其是我有几千张唱片。

更新!context是EntityFramework上下文和上下文。A表示DbSet我仍然收到错误"LINQ to Entities无法识别方法"Boolean Contains"我也不能使用

context.A.ToList().Where(....

因为我有数千条记录,这将导致效率低下

在linq';中使用Contains方法;s Where条款

这对我有效:

public class A
{
    public List<B> MyCollection{get; set;}
}
public class B
{
     public string Id;
}
void Main()
{
    // this is what you're searching for
    var myB = new B{Id="1"};

    // here are some A objects to put in your collection
    A a1 = new A();
    a1.MyCollection = new List<B>();
    A a2 = new A();
    a2.MyCollection = new List<B> { myB };
    A a3 = new A();
    a3.MyCollection = new List<B> { new B {Id="1"}};

    // here's a List that represents your context.A
    List<A> contextA = new List<A> {a1, a2, a3};

    // here's your actual search. results has a count of 1
    var results = contextA.Where( x=> x.MyCollection.Contains(myB));
    Console.WriteLine(results.Count()); 
}

注意,这只会找到a2,因为你把对象"myB"放在那里。它找不到a3,这是一个使用相同id创建的新对象。

如果你想同时找到a2和a3,你可能想把Where改成这样:

var results = contextA.Where( x=> x.MyCollection.Any(b => b.Id == myB.Id));
var ans = from b in context.A.MyCollection
          where b.Id == 1
          select b;

var ans = context.A.MyCollection.Where(b => b.Id == 1);

你试过这个吗

context.A.MyCollection.Where( x= > x.Id == myB.Id).ToList();