Linq查询具有where条件的表中的不同数据

时间:2013-07-12 13:38:04

标签: c# linq

我有一个像这样的sql语句:

select distinct(agent_name)
from properties
where agent_name not in ('null','')

我希望在C#页面中使用linq查询

4 个答案:

答案 0 :(得分:4)

假设您正在比较原始查询的字符串值'null'

List<string> agentNames = db.Properties.Where(p=>p.AgentName != "null" && 
                                        p.AgentName != "")
                                       .Select(p => p.AgentName)
                                       .Distinct()
                                       .ToList();

如果您实际上正在与空值进行比较,只需将其更改为:

List<string> agentNames = db.Properties.Where(p=>p.AgentName != null && 
                                        p.AgentName != "")
                                       .Select(p => p.AgentName)
                                       .Distinct()
                                       .ToList();

答案 1 :(得分:2)

var result = context.Properties.Where(p => p.AgentName != null 
                                        && p.AgentName != "")
                               .GroupBy(p => p.AgentName)
                               .Select(g => g.Key);

答案 2 :(得分:0)

尝试这样的事情

   var result =    (from dbo in database.Table
                     where dbo.agent_name!=null and dbo.agent_name !=''
                     select dbo.agent_name).Distinct();

或者如果你已经有一个清单

  var result = (list.Where(a => a.agent_name!=null && a.agent_name!='').Select(
                a.agent_name)).Distinct();

答案 3 :(得分:0)

你可以这样使用

var forms = db.properties.
                Where(a => a.agent_name == 'null' || a.agent_name == null).
                Select(x => x.agent_name).
                Distinct().
                ToList();

其等效的 SQL 语句,由 LINQ to SQL 设计为

SELECT 
    [Distinct1].[agent_name] AS [agent_name]
    FROM ( SELECT DISTINCT 
        [Extent1].[agent_name] AS [agent_name]
        FROM [dbo].[properties] AS [Extent1]
        WHERE [Extent1].[agent_name] = N'null' OR [Extent1].[agent_name] = N''
    )  AS [Distinct1]