C#MVC获取.Distinct()数据

时间:2016-02-23 04:57:53

标签: c# sql-server json asp.net-mvc

我在SQL Server中有一些数据:

%timeit df['COL2'] = np.where(pd.isnull(df['COL1']), np.nan, df['COL2'])
100 loops, best of 3: 10.9 ms per loop

我需要在C#MVC中使用以下SQL

[
  {
    "code": 1,
    "name": "qweee",
    "IDNO": "ff2222"
  },
  {
    "code": 2,
    "name": "test2",
    "IDNO": "ff2222211"
  },
  {
    "code": 3,
    "name": "fsdfasdf",
    "IDNO": "ddaaa"
  },
  {
    "code": 4,
    "name": "qweee",
    "IDNO": "ff2222"
  },
  {
    "code": 5,
    "name": "123",
    "IDNO": "U120000005"
  }
]

然后我会得到

SELECT DISTINCT  
    A1.IDNO , A1.name ,
    (SELECT COUNT(cnt_tab.IDNO) 
     FROM Postpartum_AccountsManagement AS cnt_tab
     WHERE cnt_tab.IDNO = A1.IDNO) AS data_cnt
FROM 
    Postpartum_AccountsManagement AS A1

我需要在C#MVC中获取相同的数据。

1 个答案:

答案 0 :(得分:1)

请检查以下代码

使用NewtonSoft将您的json字符串转换为序列化对象并使用Linq查询。

 IList<AccountsManagement> yourData = JsonConvert.DeserializeObject<List<AccountsManagement>>(yourJsonString);

 IList<YourResult> finalResult =  yourData.GroupBy(m => new {m.Name, m.IDNO).Select(group => new YourResult(){
       Name = group.FirstOrDefault().Name,
       IDNO = group.FirstOrDefault().IDNO,
       Data_cnt = group.Count()
    }).ToList();

您的课程将

public class AccountsManagement
{
  public int Code {get;set;}
  public string Name {get;set;}
  public string IDNO {get;set;}
}

public class YourResult
{
   public string Name {get;set;}
   public string IDNO {get;set;}
   public int Data_cnt {get;set;}
}