In statement for LINQ to objects

2019-03-30 05:23发布

Is there an equivalent of a SQL IN statement in LINQ to objects?

2条回答
甜甜的少女心
2楼-- · 2019-03-30 05:41

Yes - Contains.

var desiredNames = new[] { "Jon", "Marc" };

var people = new[]
{
    new { FirstName="Jon", Surname="Skeet" },
    new { FirstName="Marc", Surname="Gravell" },
    new { FirstName="Jeff", Surname="Atwood" }
};

var matches = people.Where(person => desiredNames.Contains(person.FirstName));

foreach (var person in matches)
{
    Console.WriteLine(person);
}

(In LINQ to SQL this ends up as an "IN" query.)

Note that in LINQ to Objects the above isn't really very efficient. You'd be better off with a join:

var matches = from person in people
              join name in desiredNames on person.FirstName equals name
              select person;

(This could still be done with dot notation of course, but it ends up being somewhat messier.)

查看更多
干净又极端
3楼-- · 2019-03-30 05:55

I will go for Inner Join in this context. If I would have used contains, it would iterate 6 times despite if the fact that there are just two matches. I just want to emphasize here that I will go for Joins instead of IN predicate.

var desiredNames = new[] { "Pankaj" };

var people = new[] 
{ 
    new { FirstName="Pankaj", Surname="Garg" }, 
    new { FirstName="Marc", Surname="Gravell" }, 
    new { FirstName="Jeff", Surname="Atwood" } 
};

var records = (from p in people join filtered in desiredNames on p.FirstName equals filtered select p.FirstName).ToList();
查看更多
登录 后发表回答