tags:

views:

1590

answers:

2

Given the Below Tables. How do I get the Distinct name given the other ID of 76 in LINQ?

**Table S**
SID   OtherID
------------------------------
1     77
2     76


**Table Q**
QID   SID  HighLevelNAme      LoweLevelName
---------------------------------------
10     1       Name1              Engine
11     1       Name1              SparkPlus
12     1       Name2              Seat
13     1       Name2              Belt
14     1       Name1              Oil

I want to return a list of

Name1 Name2

The SQL to do this is

SELECT DISTINCT
    Q.HighLevelNAme
FROM S
JOIN Q ON Q.SID = S.SID
WHERE
     S.OtherID = 76

I also have Objects that represents each table.

An answer in VB or C# is acceptable.

+4  A: 

If you have the foreign key relationships defined in your database, and generated the LINQ classes via the designer, then the joins should be represented in the object model, right? So each QItem has a property SItem? If not, I guess you can use the Join extension method for that part.

Anyhow, I didn't test this IRL, but wouldn't it just be this?

var results = (from QItem in dataContext.QItems
                where QItem.SItem.OtherID == 76
                select QItem.HighLevelName).Distinct();
Troy Howard
This works. I don't know how I missed this. That is exactly as I have it modeled.Thanks very much.
David Basarab
+2  A: 

Using the answer by Troy, this LINQ to Object also works.

List<string> highLevelNames = dataContext
  .Q
  .Where<Q>(item => item.S.OtherID == id)
  .Select<Q, string>(item => item.HighLevelNAme)
  .Distinct()
  .ToList<string>();
David Basarab
That's "query methods", not "Linq to Objects". You aren't querying an in-memory collection of objects.
David B