本文介绍了在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 )
{
........
}

推荐答案


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语句中不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:12