【问题标题】:distinct and startswith in the same linq query在同一个 linq 查询中不同和开头
【发布时间】:2014-08-13 20:33:24
【问题描述】:

我需要在 LINQ 中为 ASP.net MVC 应用程序编写以下 SQL 查询:

select distinct(COST_CENTER) from FDCostCenterRequest where COST_CENTER like '10%'

FDCostCenterRequest中COST_CENTER列的定义如下:

public string COST_CENTER { get; set; }

我是这样写的:

IEnumerable<FDCostCenterRequest> suggestions = 
    from cc in db.FDCostCenterRequests.Where(cc => 
    cc.COST_CENTER.StartsWith(searchString)).ToList() select cc;

var selected = from costList in suggestions select costList.COST_CENTER.Distinct();

List<string> dropDownInfos = new List<string>();
foreach (var item in selected)
{
    dropDownInfos.Add(item.ToString());
}

但是当我尝试查看 dropDownInfos 内容时,每条记录都会得到 System.Linq.Enumerable+&lt;DistinctIterator&gt;d__811[System.Char]`。我在这里做错了什么?

【问题讨论】:

  • 您要将哪个属性添加到 dropdowninfos?

标签: c# sql asp.net linq


【解决方案1】:
var yourItems = db.FDCostCenterRequests.Where(cc => cc.COST_CENTER.StartsWith(searchString)).Select(o=>o.COST_CENTER).Distinct().ToList();

【讨论】:

    【解决方案2】:

    您不是从每个中心获得不同的成本中心,而是将每个中心转换为构成成本中心的一组不同的字符。

    您可以用不同的方式为查询加上括号,但如果您不在查询和方法语法之间切换太多,会更容易:

    var query = db.FDCostCenterRequests
        .Where(cc => cc.COST_CENTER.StartsWith(searchString))
        .Select(cc => cc.COST_CENTER)
        .Distinct();
    

    【讨论】:

      【解决方案3】:

      由于 string 实现了 IEnumerable,因此您的 Distinct 正在对其进行操作。将查询的其余部分用括号括起来,以便 Distinct 对查询进行操作。

      var selected = (from costList in suggestions
                       select costList.COST_CENTER).Distinct(); 
      

      【讨论】:

        【解决方案4】:

        我通过以下方式得到它:

        var suggestions = from cc in db.FDCostCenterRequests.Where(cc => cc.COST_CENTER.StartsWith(searchString)).GroupBy(x=>x.COST_CENTER).Select(g=>g.Key)
                                  select cc;
        

        我知道这有点绕,但仍然感谢您的回答。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-16
          • 1970-01-01
          相关资源
          最近更新 更多