使用LINQ获取List中的所有DISTINCT项

时间:2015-12-08 15:42:26

标签: c#

我是LINQ的新手,我有以下脚本,如果条件满足,它会返回表格中的第一项,但是,我想获得所有不同的项目,而不仅仅是第一项。我在这个平台上比较新。

public LG GetLG (int WID)
{
    lock (locker) {
      return database.Table<LG> ().FirstOrDefault (x => x.id == WID);
    }
}

2 个答案:

答案 0 :(得分:2)

@{ ViewBag.Title = "Page"; } @section Scripts { <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1.1', { packages: ['line'] }); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('number', 'Day'); data.addColumn('number', 'Guardians of the Galaxy'); data.addColumn('number', 'The Avengers'); data.addColumn('number', 'Transformers: Age of Extinction'); data.addRows([ [1, 37.8, 80.8, 41.8], [2, 30.9, 69.5, 32.4], [3, 25.4, 57, 25.7], [4, 11.7, 18.8, 10.5], [5, 11.9, 17.6, 10.4], [6, 8.8, 13.6, 7.7], [7, 7.6, 12.3, 9.6], [8, 12.3, 29.2, 10.6], [9, 16.9, 42.9, 14.8], [10, 12.8, 30.9, 11.6], [11, 5.3, 7.9, 4.7], [12, 6.6, 8.4, 5.2], [13, 4.8, 6.3, 3.6], [14, 4.2, 6.2, 3.4] ]); var options = { chart: { title: 'Box Office Earnings in First Two Weeks of Opening', subtitle: 'in millions of dollars (USD)' }, width: 900, height: 500 }; var chart = new google.charts.Line(document.getElementById('linechart_material')); chart.draw(data, options); } </script> } <h2>Page</h2> <table> <tr> <td style="width: 50%"> <div id="linechart_material"></div> </td> </tr> <tr> <td style="width: 50%"> <iframe id="videoiframe" src="https://www.google.com/starwars/" /> </td> </tr> </table> 您要找的是什么?

.Distinct()

以下link包含有用的资料:

示例:

return database.Table<LG>.Where(x => x.id == WID).Distinct()

此代码生成以下输出:

  

不同年龄:
  21个
  46个
  55个
  17

答案 1 :(得分:-1)

LG对象中,您需要覆盖EqualsGetHashCode方法。
完成后,您可以使用LINQ中的Distinct()函数

database.Table<LG>.Where(x => x.id == WID).Distinct()