asp.net-mvc LINQ Distinct()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5144409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:56:49  来源:igfitidea点击:

LINQ Distinct()

asp.net-mvclinq

提问by Pinu

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

我正在努力在 LINQ 中获取此 sql 查询的结果

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

this is my repository query:

这是我的存储库查询:

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

filter:

筛选:

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?

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

回答by Jon Skeet

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.Typeis.

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

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

回答by msarchet

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

This matches what your provided SQL Query should be doing.

这与您提供的 SQL 查询应该执行的操作相匹配。