LINQ Distinct()

20

我正在尝试使用LINQ获取这个SQL查询的结果。

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;
            }

我需要筛选器返回不同的产品类型?我该怎么做?

2个回答

38

简单来说就是这样:

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的类型匹配。

如果查询表达式本身相当简单,您可能会发现使用扩展方法来处理整个查询更易读:

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

9
return (from p in qry
       where p.CatId.Equals(CatID)
       select p.Type).Distinct();

这符合您提供的 SQL 查询应该执行的内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接