EF计数重复字段值的实例

时间:2015-03-02 15:20:30

标签: c# entity-framework tsql count entity-framework-5

EntityFramework是否提供任何机制来查找值在列中重复的次数?我知道在纯SQL中分组/计数,但我不知道如何将其转换为EF Lambda表达式。

该项目在.NET4上使用EF5

  

运行下面的代码段以查看所需的输出

<h3>Original Table</h3>
<table border="1">
  <thead>
    <tr>
      <th>
        Some Column
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>asdf</td>
    </tr>
    <tr>
      <td>asdf</td>
    </tr>
    <tr>
      <td>fdsa</td>
    </tr>
    <tr>
      <td>fdsa</td>
    </tr>
    <tr>
      <td>fdsa</td>
    </tr>
  </tbody>
</table>

<h3>Desired Table</h3>
<table border="1">
  <thead>
    <tr>
      <th>Some Column</th>
      <th>Count</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>asdf</td>
      <td>2</td>
    </tr>
    <tr>
      <td>fdsa</td>
      <td>3</td>
    </tr>
  </tbody>
</table>

2 个答案:

答案 0 :(得分:1)

你会想要像这样使用LINQ语法:

from item in Table
group item by item.FieldName into g
select new {Key = g.Key, Count = g.Count()}

将Table替换为您的EntitySet名称,将FieldName替换为您要分组的属性。

编辑: 并请求Lambda语法:

Table.GroupBy(l => l.FieldName , l => l, (key,g) => new {Key = key, Count=g.Count()})

答案 1 :(得分:1)

我不会为您的原始表格显示您的POCO,但可以从您的问题中看出它至少有一个“Some Column”属性:

// a list, simulating your table, and seeded with values from your example
var originalData = new List<OriginalTable>
{
    new OriginalTable {SomeColumn = "asdf"},
    new OriginalTable {SomeColumn = "asdf"},
    new OriginalTable {SomeColumn = "fdsa"},
    new OriginalTable {SomeColumn = "fdsa"},
    new OriginalTable {SomeColumn = "fdsa"},
};

以下内容将返回SomeColumn属性中具有不同值key的对象集合,以及originalData属性中count的值的计数:

var desiredTable = originalData.GroupBy(o => o.SomeColumn,
                                        o => 1, // don't need the whole object
                                        (key, g) => new {key, count = g.Sum()});

当然,您可以在第二个参数中从组中选择返回整个对象,但这是过度的,因为您只是计算返回的内容。

看起来你可能会想要在字典中使用这个 - 这与GroupBy非常相似 - 所以我也会把它扔出去:

var desiredDictionary = desiredTable.ToDictionary(x => x.key, x => x.count);