简体   繁体   English

如何在linq to sql中计算多个不同的列?

[英]How to count more than one distinct columns in linq to sql?

I am struggling with Linq, hence it is a lame question but still .. I have a table with following 4 columns 我在Linq上苦苦挣扎,因此这是一个la脚的问题,但仍然..我有一个包含以下4列的表格

Pid   SKU    colorid   sizeid
1     'A65102'    38       2
2     'A65102'    38       4
3     'A65102'    38       18

I have to get how many different color and size option are available for this. 我必须获得多少个不同的颜色和尺寸选项。

In sql, I use to do it by: 在sql中,我使用以下方法:

select count(distinct [sizeid]) ,count(distinct [colors]) 
from [item_master] 
where sku = 'A65102' 

But in Linq, I can get all the values by 但是在Linq中,我可以通过

var dd = (from im in db.item_masters 
          where im.sku.Contains("A65102") 
          select new {im.sizeid,im.colors });

But how can I get the count of distinct values for both in single query? 但是,如何在单个查询中获得两个不同值的计数?

You could use GroupBy : 您可以使用GroupBy

var distinctCounts = db.item_masters.GroupBy(im => im.sku)
    .Where(grp => grp.Key == "A65102")
    .Select(grp => new { 
        CntSizes  =  grp.Select(im => im.sizeid).Distinct().Count(),
        CntColors =  grp.Select(im => im.colorid).Distinct().Count()
    });

You can use the query that you have as a data source for retrieving this data (especially useful if you would want to use it for other things as well afterwards): 您可以将查询用作数据源以检索此数据(如果以后还要将其用于其他用途,则特别有用):

var dd = (from im in db.item_masters 
          where im.sku == "A65102" 
          select new {im.sizeid, im.colors}).ToList();

var numDistinctSizes = dd.Select(x => x.sizeid).Distinct().Count();
var numDistinctColors = dd.Select(x => x.colors).Distinct().Count();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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