在Web API中返回不同行

本文关键字:返回 Web API | 更新日期: 2023-09-27 18:02:17

我们目前正在查询Oracle DB,并以JSON格式返回结果。查询结果返回更多重复的行。控制器类似于

下面
public HttpResponseMessage Getdetails([FromUri] string[] Column)
    {
     List<string> selectionStrings = new List<string>();
     string connStr = ConfigurationManager.ConnectionStrings["PConnection"].ConnectionString;
     using (OracleConnection dbconn = new OracleConnection(connStr))
     {
      DataSet userDataset = new DataSet();
      var colDict = new Dictionary<string, string>()
      {
       {"CATEGORY", "STCD_PRIO_CATEGORY_DESCR.DESCR"},
       {"SESSION_NUMBER", "STCD_PRIO_CATEGORY_DESCR.SESSION_NUM"},
       {"SESSION_START_DATE","Trunc(STCD_PRIO_CATEGORY_DESCR.START_DATE)"},
       {"SESSION_START_TIME","STCD_PRIO_CATEGORY_DESCR.START_DATE"}}};
            foreach (string col in Column)
            {
                string selector = colDict[col];
                selectionStrings.Add(string.Format("{0} AS {1}", selector, col));
            }
            string selectString = string.Join(",", selectionStrings);
            var strQuery =   string.Format(@"SELECT {0}
                             FROM 
                             STCD_PRIO_CATEGORY_DESCR", selectString);
     }}}

如果我在Select语句中添加Distinct作为

 var strQuery =   string.Format(@"SELECT DISTINCT {0}
                             FROM 
                             STCD_PRIO_CATEGORY_DESCR", selectString);

应该足够了吗?还是应该在所有列名前加上DISTINCT

在Web API中返回不同行

使用distinct,或者如果您仍然有问题,您可以将数据结果移动到列表中,并使用linq仅选择唯一的行。

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();

取自:Select distinct using linq