使用与Linq到SQL的区别

时间:2013-10-29 13:09:41

标签: c# linq

如何将此查询从sql更改为linq?

category
select distinct prodCategory from table4

subcategory
SELECT distinct [prodSubCat] FROM [table4] WHERE ([prodCategory] = @prodCategory)


prodCategory    prodSubCat
-------------------------------------
Home            Cassette Receiver
Home            Receiver
Home            cd player
Home            cd player
Home            Receiver
Car             dvd player
Car             GPS 

实施例

我的目标是为prodCategory =" Car"

获取prodSubCat
Car             dvd player
Car             GPS

2 个答案:

答案 0 :(得分:8)

使用Distinct()

MSDN

  

从序列中返回不同的元素。

IEnumerable<string> category = (from p in t.table4
                                select p.prodCategory).Distinct();

IEnumerable<string> subCategory = (from p in t.table4
                                   where p.prodCategory == "Car"
                                   select p.prodSubCat).Distinct();

答案 1 :(得分:1)

使用Distinct - &gt;通过使用默认的相等比较器来比较值,从序列中返回不同的元素。 (MSDN:http://msdn.microsoft.com/en-us/library/bb348436.aspx

var results = dataContext.Table4.Where(t => t.prodCategory.Equals(prodCategory)).Distinct();