LINQ Distinct()

后端 未结 2 1516
挽巷
挽巷 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:42

    Simply like this:

    public static IQueryable GetDistinctProdType(
        this IQueryable 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 GetDistinctProdType(
        this IQueryable query,
        int categoryId)
    {
        return query.Where(p => p.CatID == categoryId)
                    .Select(p => p.Type)
                    .Distinct();
    }
    

提交回复
热议问题