5

LINQ to objects 中是否有等效的 SQL IN 语句?

4

2 回答 2

16

是 -包含

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);
}

(在 LINQ to SQL 中,这最终作为“IN”查询。)

请注意,在 LINQ to Objects 中,上述内容并不是非常有效。加入会更好:

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

(当然,这仍然可以使用点符号来完成,但最终会有点混乱。)

于 2009-01-08T10:59:19.843 回答
0

在这种情况下,我会选择 Inner Join。如果我使用contains,它会迭代 6 次,尽管事实上只有两个匹配项。我只是想在这里强调一下,我将使用 Joins 而不是 IN 谓词。

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();
于 2012-04-03T12:57:48.340 回答