LINQ鲜明的() [英] LINQ Distinct()

查看:93
本文介绍了LINQ鲜明的()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作得到这个SQL查询的结果在LINQ

I am working on getting the results of this sql query in LINQ

SELECT DISTINCT(Type)
FROM  Product
WHERE categoryID = @catID

这是我的资料库查询:

public IQueryable<ProdInfo> GetProdInfo()
        {

            var data = from u in db.Prod
                       select new ProdInfo
                       {
                           PID = u.PID,
                           CatID = u.CatID,                           
                           LastChanged = u.LastChanged,
                           ChangedBy = u.ChangedBy,                               
                           Type = u.Type,
                       };

            return data;
        }

过滤器:

public static IQueryable<ProdInfo> GetDistinctProdType(this IQueryable<ProdInfo> qry,int CatID)
            {
                return from p in qry
                       where p.CatID.Equals(CatID)
                       select p;
            }

我需要的过滤器返回不同的督促类型?我怎样才能做到这一点?

I need the filter to return the distinct prod type? How can i do this?

推荐答案

只要是这样的:

public static IQueryable<ProdType> GetDistinctProdType(
    this IQueryable<ProdInfo> query,
    int categoryId)
{
    return (from p in query
            where p.CatID == categoryId
            select p.Type).Distinct();
}

请注意,我已经改变了返回类型 - 它应该与任何类型 ProdInfo.Type

您可能会发现它更具有可读性用于整个查询的扩展方法,如果查询前pression本身是相当简单的:

You may find it more readable to use the extension methods for the whole query if the query expression itself is reasonably simple:

public static IQueryable<ProdType> GetDistinctProdType(
    this IQueryable<ProdInfo> query,
    int categoryId)
{
    return query.Where(p => p.CatID == categoryId)
                .Select(p => p.Type)
                .Distinct();
}

这篇关于LINQ鲜明的()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆