简体   繁体   中英

Linq JOIN, COUNT, TUPLE in C#

I have table with columns: A, B and other columns(not important for this)

for example

A           B           C         D
Peter      apple   
Thomas     apple
Thomas     banana
Lucy       null

How can I get list of tuples {A, count of B} using join?

For my table it is: {Peter, 1}, {Thomas, 2}, {Lucy, 0}

Thanks

You've to just group by records on column A and count where B is not null

        var result = (from t1 in cartItems
                      group t1 by t1.A into t2
                      select new
                      {
                          t2.Key,
                          count = t2.Count(p=> p.B != null)
                      }).ToList();

Since you mentioned table, I assume it is DataTable .

You could use simple Linq statements for what you need. Query returns List<Tuple> and Tuple contains two fields Item1 representing Name and Item2 representing Count

var results = dt.AsEnumerable()
    .GroupBy(row=>row.Field<string>("A"))
    .Select(s=> new Tuple<string, int>(s.Key, s.Count(c=>c!=null)))         
    .ToList();

Check this Demo

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