在Where语句中不同 [英] Distinct within a Where statement

查看:91
本文介绍了在Where语句中不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于该语句现在返回的是由N.TypeMis过滤的所有项目,但我希望它仅返回具有不同的N.Lvl的项目.

我尝试使用GroupBy,但无法弄清楚.

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.

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 )
{
........
}

推荐答案

也许这会有所帮助:

http://blogs.msdn.com/b/charlie/archive/2006/11/19/linq-farm-group-and-distinct.aspx [
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...


要像上面提到的那样使用Distinct,您必须创建另一个实现IEqualityComparer<whatevertypenwas>
的类 然后将其的新实例传递给您的查询.例如:

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:

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());

    }
}



或实现公共类DelegateComparer : IEqualityComparer{},然后添加扩展名:



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

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



然后您可以拨打



and then you can call

.Distinct((a, b) => a.Mission_ID== b.Mission_ID, c => c.Mission_ID.GetHashCode());


这篇关于在Where语句中不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆