简体   繁体   中英

Linq | Iterative Groupby on a List<>

I have an object

public class MasterData
{
    public string loanId { get; set; }
    public string docId { get; set; }
    public string fileName { get; set; }
    public string doctype { get; set; }
}

I have a List<MasterData> lstMstrDatawhich may look like this

<table>
  <tr>
    <th>loanId</th>
    <th>docId</th>
    <th>docType</th>
    </tr>
  <tr>
    <td>101</td>
    <td>8001</td>
    <td>BankStatement</td>
    </tr>
    <tr>
      <td>102</td>
      <td>8002</td>
      <td>CreditReport</td>
    </tr>
  <tr>
    <td>103</td>
    <td>8003</td>
    <td>PaySlip</td>
    </tr>
    <tr>
      <td>103</td>
      <td>8003</td>
      <td>Payslip</td>
    </tr>
  <tr>
    <td>104</td>
    <td>8004</td>
    <td>CreditReport</td>
    </tr>
    <tr>
      <td>105</td>
      <td>8006</td>
      <td>Mortgage</td>
    </tr>
  <tr>
    <td>105</td>
    <td>8007</td>
    <td>Mortgage</td>
    </tr>
  </table>

I want to fetch the list from this using GroupBy . I want to get a List of doctype's with the count of unique DocId's associated with it.

So the above List would basically results in :

|Doctype         |UniqueDocIdCount
----------------------------------
|BankStatement   |1
|CreditReport    |2
|PaySlip         |1
|Mortgage        |2

I tried doing it like this but doesn't yield correct result

var groupDoctype = lsMstrData
                    .GroupBy(g => new {g.doctype, g.docId})                    
                    .Select(s => s.ToList())
                    .ToList(); 
var groupDoctype = lsMstrData
                .GroupBy(g => g.doctype)
                .Select(g => new { Doctype = g.Key, UniqueDocIdCount = g.Select(k => k.docId).Distinct().Count() })
                .ToList(); 

If the docID is guaranteed to be unique then you can remove the "Distinct" and just leave g.Count().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM