Click here to Skip to main content
15,905,420 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As the statement is now it returns all items that is filtered by the N.TypeMis but I would like to have it only returning the items with a distinct N.Lvl.

I've tried using GroupBy but couldn't figure it out.

C#
var q = ( from N in _fMissionSubList
                where N.TypeMis == mTypeMis
                select new {
                  N.ID, N.Mission_ID, N.Enabled, N.Title, N.Description, N.TypeMis,
                  N.TypeParent, N.Lvl, N.LvlOrder, N.ControlType
                } ); //Would like to add something like this .Distinct(N.Lvl);

foreach ( var n in q )
{
........
}
Posted

Maybe this will help:

http://blogs.msdn.com/b/charlie/archive/2006/11/19/linq-farm-group-and-distinct.aspx[^]

EDIT==================

I don't understand why this was voted 1...
 
Share this answer
 
v2
Comments
wizardzz 9-Dec-10 10:28am    
That seems to happen a lot around here when people are expecting a code snippet to solve the problem.
to use Distinct as you mentioned above you have to create another class the implements IEqualityComparer<whatevertypenwas>
and then pass a new instance of that to your query. For example:

C#
class NyClassN
{
    public string TypeMis { get; set; }
    public int ID { get; set; }
    public string Mission { get; set; }
}
<br /> 
class NyClassNEqComp : IEqualityComparer<NyClassN>
{
    public bool Equals(NyClassN x, NyClassN y)
    {
        return x.Mission.Equals(y.Mission) &&  x.TypeMis.Equals(y.TypeMis);
    }<br />
    public int GetHashCode(NyClassN obj)
    {
        return string.Format("{0}{1}", obj.Mission, obj.TypeMis).GetHashCode();
    }
}<br />
class Program
{
    static void TestAg(string mTypeMis)
    {
        var q = (from N in new List<NyClassN>()
                 where N.TypeMis == mTypeMis
                 select N).Distinct (new NyClassNEqComp());

    }
}


Or implement a public class DelegateComparer : IEqualityComparer{} then add an extension:

C#
public static IEnumerable Distinct(this IEnumerable items, Func equals, Func hashCode) 
{ 
    return items.Distinct(new DelegateComparer(equals, hashCode)); 
} 


and then you can call

C#
.Distinct((a, b) => a.Mission_ID== b.Mission_ID, c => c.Mission_ID.GetHashCode());
 
Share this answer
 
v2
Comments
#realJSOP 9-Dec-10 16:17pm    
I moved your additional "comment" to your original post by using the "Improve Answer" link.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900