C#中的LINQ排序依据过滤空或空值是最后一次 [英] C# Linq OrderBy filtering null or empty values to be last

查看:1073
本文介绍了C#中的LINQ排序依据过滤空或空值是最后一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尽量让我的自定义排序依据扩展方法,我顺利的工作我的代码,但除此之外,我想列出结果为空或空或零值最后,任何人都可以帮我这个问题?

I try to make my custom orderby extension method, i successfully worked my code but in addition i want to list null or empty or zero values last in result, anyone can help me about that issue ?

下面是我的扩展方法来排序依据

Here is my extension method to orderby

    public static IQueryable<T> OrderBy<T>(this IQueryable<T> q, string SortField, bool isAsc)
    {
        //var nullExpr = Expression.Constant(null, typeof(T));
        var param = Expression.Parameter(typeof(T), "p");
        var prop = Expression.Property(param, SortField);
        var exp = Expression.Lambda(prop, param);
        string method = isAsc ? "OrderBy" : "OrderByDescending";
        Type[] types = new Type[] { q.ElementType, exp.Body.Type };
        var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
        return q.Provider.CreateQuery<T>(mce);
    }



在此先感谢

Thanks in advance

推荐答案

如果不使用扩展方法....

Without using an extension method....

创建自定义的的IComparer<串> 来使用默认前检查空值的String.Compare 。第一次检查将返回-1而不是1或1而不是-1,如果使用的是标准的字符串比较。

Create a custom IComparer<string> to check the empty values before using the default String.Compare. The first checks will return -1 instead of 1 or 1 instead of -1, if using the standard string comparison.

/// <summary>
/// Returns -1 instead of 1 if y is IsNullOrEmpty when x is Not.
/// </summary>
public class EmptyStringsAreLast : IComparer<string>
{
    public int Compare(string x, string y)
        {
            if (String.IsNullOrEmpty(y) && !String.IsNullOrEmpty(x))
            {
                return -1;
            }
            else if (!String.IsNullOrEmpty(y) && String.IsNullOrEmpty(x))
            {
                return 1;
            }
            else
            {
                return String.Compare(x, y);
            }
        }
 }



通过你的 EmptyStringsAreLast 比较器入λ的排序依据的表达。在该方案中谁已经进入了比赛的球队应该出现按字母顺序排列,但无党派比赛参赛作品必须在然后结束出现。

Pass your EmptyStringsAreLast comparer into the OrderBy of Lambda expression. In this solution teams who have entered the race should appear alphabetical order, but the unaffiliated race entries should appear at then end.

var entries = repository.Race.Where(e => e.EventId == id)
                          .OrderBy(e => e.TeamName, new EmptyStringsAreLast())
                          .ThenBy(e => e.LastName)
                          .ThenBy(e => e.FirstName);

这篇关于C#中的LINQ排序依据过滤空或空值是最后一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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