Linq fetch distinct

c#, distinct, linq, random

Solution

One approach would be to use GroupBy and then select the first item from each group:

var q = (
    from c in db.tblStoreRecommendations
    where
        itemIDsInCart.Contains(c.ItemID)
     && !itemIDsInCart.Contains(c.RecommendItemID)
    select c
).GroupBy(c => c.RecommendItemID)
 .Select(g => g.First());

If you're using this to display a random review, I would recommend foisting this into the using code rather than the LINQ query, by omitting the `First` like so:

var q = (
    from c in db.tblStoreRecommendations
    where
        itemIDsInCart.Contains(c.ItemID)
     && !itemIDsInCart.Contains(c.RecommendItemID)
    select c
).GroupBy(c => c.RecommendItemID)
 .Select(g => g.ToArray());

var random = new Random();
foreach (var r in q)
{
    var rec = r[random.Next(r.Length)];
    // use your recommendation
}

Problem

I have the query: ``` var q = ( from c in db.tblStoreRecommendations where itemIDsInCart.Contains(c.ItemID) && !itemIDsInCart.Contains(c.RecommendItemID) select c ); ``` It will return something along the lines of: ``` ID ItemID RecommendItemID Message ------------------------------------------ 1 25 3 Msg here 2 26 3 Something else 3 27 8 Another message ``` I need the query to filter out results that have the same `RecommendItemID`, this should not appear in returned results more than once. If two exist, it can use either (random selection would be best). So the returned results should omit record ID 1 or 2. Can anyone show me how to do this please? Thanks!

Original source