LINQ Distinct()

后端 未结 2 1506
挽巷
挽巷 2021-02-12 13:42

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

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

this is my

相关标签:
2条回答
  • 2021-02-12 14:21
    return (from p in qry
           where p.CatId.Equals(CatID)
           select p.Type).Distinct();
    

    This matches what your provided SQL Query should be doing.

    0 讨论(0)
  • 2021-02-12 14:42

    Simply like 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();
    }
    

    Note that I've changed the return type - it should match whatever the type of ProdInfo.Type is.

    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();
    }
    
    0 讨论(0)
提交回复
热议问题