在LINQ中使用Union和Contains

时间:2011-12-14 15:03:34

标签: c# linq

我有以下SQL查询,它同时使用了Union和“IN”语句

select FirstName 
From Person
where Lastname in ('Smith','Jones')
and MiddleInitial In ('A','G','M',)

UNION

Select PersonFirstName as Firstname
FROM BusinessPerson
WHERE CorporateName in ('Jones','Thomas')
And CorporateDirection IN ('N','S')

我有一个自定义对象,包括PersonFirstName,LastName,MiddleInitial,corporateName和corporatedirection作为属性。

我试图将未经过滤的联合加载到内存中,然后从集合中写入linq查询,而不是每次请求都转到数据库。

由于我想过滤集合中每个对象的属性,我试图使用每个属性的包含但没有取得多大成功。

我有一个Letters的字符串数组,以及我的一些过滤器的Names的字符串数组,但未能将它们正确地应用于Linq查询,并且我不确定如何使用包含来处理对象中的属性集合。

我正在尝试像

这样的东西
string[] corporateNameCollection = new string[] { "Kmart", "Walmart" };

var filteredObject =  personCollection.Where(b=>b.CorporateName.Contains(corporateNameCollection ));  

有关对集合对象的属性使用字符串数组的任何建议吗?

谢谢,

3 个答案:

答案 0 :(得分:3)

你想:

.Where(b => corporateNameCollection.Contains(b.CorporateName));

然后,corporateNameCollection包含b.CorporateName中的每一个。 并且应该在Linq-SQL中翻译为IN

答案 1 :(得分:0)

您是否尝试检查字符串数组是否包含与CorporateName匹配的元素,如下所示:

string[] corporateNameCollection = new string[] { "Kmart", "Walmart" };
var filteredObject = personCollection
    .Where(b => corporateNameCollection.Contains(b.CorporateName));

答案 2 :(得分:0)

string[] corporateNameCollection = new string[] { "Kmart", "Walmart" };

     var filteredObject =  personCollection.Where(b=>corporateNameCollection.Contains(  b.CorporateName));

这应该有效。