2011-02-28 3 views
20

Je travaille sur l'obtention des résultats de cette requête SQL dans LINQLINQ Distinct()

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

ceci est ma requête dépôt:

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

Filtre:

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

J'ai besoin du filtre pour retourner le disti type nct prod? Comment puis-je faire ceci?

Répondre

35

simplement comme ceci:

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

Notez que j'ai changé le type de retour - il doit correspondre quel que soit le type de ProdInfo.Type est.

Vous trouverez peut-être plus lisible à utiliser les méthodes d'extension pour toute requête si l'expression de la requête elle-même est assez simple:

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

Cela correspond à ce que votre condition de requête SQL devrait faire.