Wednesday, July 2, 2008

Linq Distinct

Lets' say I have two tables. Here, you have SectionTable and SectionName.





Linq Disctinct
SectionTable
TableID SectionID
1 1
2 1
3 2


HTML clipboard
SectionName
TableID SectionName
1 Blue
2 Red
3 Pink

On SectionTable you have duplicate value of of SectionID.
On SectionName, you have no duplicate values.

"from st in db.SectionTable select st" you will get the Grid Data of SectionTable
"from sn in db.SectionName select sn" you will get the Grid Data of SectionName.


How do you marry these two tables to get a Distinctive Values?

(from st in db.SectionTable
from sn in db.SectionName
where st.SectionID == sn.TableID
select new
{
SectionID = sn.TableID
SectionName = sn.SectionName
}).Distinct();

If you wrap
().Distinct() around your query, you get Distict value of the both!
Hope that Helps...



No comments: