简体   繁体   English

带有自定义比较器的 OrderBy 的 Linq 语法<T>

[英]Linq syntax for OrderBy with custom Comparer<T>

There are two formats for any given Linq expression with a custom sort comparer:对于具有自定义排序比较器的任何给定 Linq 表达式,有两种格式:

Format 1格式 1

var query =
    source
    .Select(x => new { x.someProperty, x.otherProperty } )
    .OrderBy(x => x, new myComparer());

Format 2格式 2

var query =
    from x in source
    orderby x // comparer expression goes here?
    select new { x.someProperty, x.otherProperty };

Question:题:
What is the syntax for the order-by expression in the second format?第二种格式的 order-by 表达式的语法是什么?

Not the question:不是问题:
How to use a custom comparer as shown in the first format.如何使用第一种格式中所示的自定义比较器。

Bonus credit:红利:
Are there actual, formal names for the two Linq formats listed above?上面列出的两种 Linq 格式是否有实际的正式名称?

What is the syntax for the order-by expression in the second format?第二种格式的 order-by 表达式的语法是什么?

It doesn't exist.它不存在。 From the orderby clause documentation :orderby 条款文档

You can also specify a custom comparer.您还可以指定自定义比较器。 However, it is only available by using method-based syntax.但是,它只能通过使用基于方法的语法来使用。


How to use a custom comparer in the first format.如何使用第一种格式的自定义比较器。

You wrote it correctly.你写得对。 You can pass the IComparer<T> as you wrote.您可以在编写时传递IComparer<T>


Are there actual, formal names for the two Linq formats listed above?上面列出的两种 Linq 格式是否有实际的正式名称?

Format 1 is called "Method-Based Syntax" ( from previous link ), and Format 2 is "Query Expression Syntax" (from here ).格式 1 称为“基于方法的语法”(来自上一个链接),格式 2 称为“查询表达式语法”(来自此处)。

How to use a custom comparer as shown in the first format.如何使用第一种格式中所示的自定义比较器。

You can't use a custom comparer in that format.您不能使用该格式的自定义比较器。

Are there actual, formal names for the two Linq formats listed above?上面列出的两种 Linq 格式是否有实际的正式名称?

Format 1 is Method syntax, Format 2 is "query syntax",格式 1 是方法语法,格式 2 是“查询语法”,

Question:题:

Thats not possible in the query syntax, because there are no overloads.这在查询语法中是不可能的,因为没有重载。

Not the question:不是问题:

You can use a comparer with anonymous types only if you use reflection to compare the objects, it's better to use a typed implementation for comparing.仅当您使用反射来比较对象时,才可以使用匿名类型的比较器,最好使用类型化实现进行比较。

If you don't want to create a typed implementation you can use a Tuple :如果你不想创建一个类型化的实现,你可以使用一个Tuple

var query =
    source
    .Select(x => new Tuple<string, int>(x.someProperty, x.otherProperty))
    .OrderBy(x => x, new MyComparer());

public class MyComparer : IComparer<Tuple<string, int>>
{
  public int Compare(Tuple<string, int> x, Tuple<string, int> y)
  {
    return x.Item1.CompareTo(y.Item1);
  }
}

Bonus credit:红利:

  • Query syntax or Comprehension Syntax查询语法或理解语法
  • Method syntax or Extension method Syntax方法语法或扩展方法语法

This isn't necessarily answering the original question, but it somewhat extends some of the possibilities outlined.这不一定回答最初的问题,但它在某种程度上扩展了概述的一些可能性。 I am posting this in case others come across the similar problem.我张贴这个以防其他人遇到类似的问题。 The solution posted here outlines a generic order by option that may be useful in other cases.此处发布的解决方案概述了在其他情况下可能有用的选项的通用顺序。 In this example, I wanted to sort a file list by different properties.在这个例子中,我想按不同的属性对文件列表进行排序。

/// <summary>
/// Used to create custom comparers on the fly
/// </summary>
/// <typeparam name="T"></typeparam>
public class GenericCompare<T> : IComparer<T>
{
    // Function use to perform the compare
    private Func<T, T, int> ComparerFunction { set; get; }

    // Constructor
    public GenericCompare(Func<T, T, int> comparerFunction)
    {
        ComparerFunction = comparerFunction;
    }

    // Execute the compare
    public int Compare(T x, T y)
    {

        if (x == null || y == null) 
        {
            // These 3 are bell and whistles to handle cases where one of the two is null, to sort to top or bottom respectivly
            if (y == null && x == null) { return 0; }
            if (y == null) { return 1; }
            if (x == null) { return -1; }
        }

        try
        {
            // Do the actual compare
            return ComparerFunction(x, y);
        }
        catch (Exception ex)
        {
            // But muffle any errors
            System.Diagnostics.Debug.WriteLine(ex);
        }

        // Oh crud, we shouldn't be here, but just in case we got an exception.
        return 0;
    }
}

Then in the implementation…然后在实施中……

        GenericCompare<FileInfo> DefaultComparer;

        if (SortOrder == SORT_FOLDER_FILE)
        {
            DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
            {
                return fr1.FullName.ToLower().CompareTo(fr2.FullName.ToLower());
            });
        }
        else if (SortOrder == SORT_SIZE_ASC)
        {
            DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
            {
                return fr1.Length.CompareTo(fr2.Length);
            });
        }
        else if (SortOrder == SORT_SIZE_DESC)
        {
            DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
            {
                return fr2.Length.CompareTo(fr1.Length);
            });
        }
        else
        {
            DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
            {
                return fr1.Name.ToLower().CompareTo(fr2.Name.ToLower());
            });
        }

        var ordered_results = (new DirectoryInfo(@"C:\Temp"))
                .GetFiles()
                .OrderBy(fi => fi, DefaultComparer);

The big advantage is that you then don't need to create a new class for each order by case, you can just wire up a new lambda.最大的优点是你不需要为每个订单创建一个新的类,你只需连接一个新的 lambda。 Obviously this can be extended in all sorts of ways, so hopefully it will helps someone, somewhere, sometime.显然,这可以以各种方式扩展,因此希望它可以帮助某人,某地,某时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM