所以今天我遇到了一个有趣的问题。我们有一个返回 IList 的 WCF Web 服务。直到我想对它进行排序之前,这并不是什么大不了的事。

事实证明 IList 接口没有内置排序方法。

我最终使用了 ArrayList.Adapter(list).Sort(new MyComparer()) 解决问题的方法,但对我来说似乎有点“贫民窟”。

我尝试编写一个扩展方法,还尝试继承 IList 并实现我自己的 Sort() 方法以及转换为 List,但这些似乎都不太优雅。

所以我的问题是,是否有人有一个优雅的解决方案来对 IList 进行排序

有帮助吗?

解决方案

使用 LINQ To Objects 为您排序怎么样?

假设你有一个 IList<Car>, ,这辆车有一个 Engine 财产,我相信你可以这样排序:

from c in list
orderby c.Engine
select c;

编辑:您确实需要快速在这里获得答案。由于我提出的语法与其他答案略有不同,我将留下我的答案 - 但是,提出的其他答案同样有效。

其他提示

您可以使用 LINQ:

using System.Linq;

IList<Foo> list = new List<Foo>();
IEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar);
IList<Foo> sortedList = sortedEnum.ToList();

这个问题启发我写了一篇博文: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

我认为,理想情况下,.NET Framework 将包含一个接受 IList<T> 的静态排序方法,但下一个最好的办法是创建您自己的扩展方法。创建几个允许您像对 List<T> 一样对 IList<T> 进行排序的方法并不太难。作为奖励,您可以使用相同的技术重载 LINQ OrderBy 扩展方法,这样无论您使用的是 List.Sort、IList.Sort 还是 IEnumerable.OrderBy,都可以使用完全相同的语法。

public static class SortExtensions
{
    //  Sorts an IList<T> in place.
    public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
    {
        ArrayList.Adapter((IList)list).Sort(new ComparisonComparer<T>(comparison));
    }

    // Convenience method on IEnumerable<T> to allow passing of a
    // Comparison<T> delegate to the OrderBy method.
    public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, Comparison<T> comparison)
    {
        return list.OrderBy(t => t, new ComparisonComparer<T>(comparison));
    }
}

// Wraps a generic Comparison<T> delegate in an IComparer to make it easy
// to use a lambda expression for methods that take an IComparer or IComparer<T>
public class ComparisonComparer<T> : IComparer<T>, IComparer
{
    private readonly Comparison<T> _comparison;

    public ComparisonComparer(Comparison<T> comparison)
    {
        _comparison = comparison;
    }

    public int Compare(T x, T y)
    {
        return _comparison(x, y);
    }

    public int Compare(object o1, object o2)
    {
        return _comparison((T)o1, (T)o2);
    }
}

使用这些扩展,可以像对列表一样对 IList 进行排序:

IList<string> iList = new []
{
    "Carlton", "Alison", "Bob", "Eric", "David"
};

// Use the custom extensions:

// Sort in-place, by string length
iList.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));

// Or use OrderBy()
IEnumerable<string> ordered = iList.OrderBy((s1, s2) => s1.Length.CompareTo(s2.Length));

帖子中有更多信息: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

你将不得不做类似我认为的事情(将其转换为更具体的类型)。

也许将其放入 T 的列表而不是 ArrayList 中,这样您就可以获得类型安全性以及如何实现比较器的更多选项。

@DavidMills 接受的答案非常好,但我认为它可以改进。其一,无需定义 ComparisonComparer<T> 当框架已经包含静态方法时的类 Comparer<T>.Create(Comparison<T>). 。该方法可用于创建 IComparison 在飞行中。

此外,它还投射 IList<T>IList 这有可能是危险的。在我见过的大多数情况下, List<T> 它实现了 IList 在幕后使用来实现 IList<T>, ,但这并不能得到保证,并且可能导致代码脆弱。

最后,超载的 List<T>.Sort() 方法有 4 个签名,但仅实现了其中 2 个。

  1. List<T>.Sort()
  2. List<T>.Sort(Comparison<T>)
  3. List<T>.Sort(IComparer<T>)
  4. List<T>.Sort(Int32, Int32, IComparer<T>)

下面的类实现了所有 4 个 List<T>.Sort() 的签名 IList<T> 界面:

using System;
using System.Collections.Generic;

public static class IListExtensions
{
    public static void Sort<T>(this IList<T> list)
    {
        if (list is List<T>)
        {
            ((List<T>)list).Sort();
        }
        else
        {
            List<T> copy = new List<T>(list);
            copy.Sort();
            Copy(copy, 0, list, 0, list.Count);
        }
    }

    public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
    {
        if (list is List<T>)
        {
            ((List<T>)list).Sort(comparison);
        }
        else
        {
            List<T> copy = new List<T>(list);
            copy.Sort(comparison);
            Copy(copy, 0, list, 0, list.Count);
        }
    }

    public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
    {
        if (list is List<T>)
        {
            ((List<T>)list).Sort(comparer);
        }
        else
        {
            List<T> copy = new List<T>(list);
            copy.Sort(comparer);
            Copy(copy, 0, list, 0, list.Count);
        }
    }

    public static void Sort<T>(this IList<T> list, int index, int count,
        IComparer<T> comparer)
    {
        if (list is List<T>)
        {
            ((List<T>)list).Sort(index, count, comparer);
        }
        else
        {
            List<T> range = new List<T>(count);
            for (int i = 0; i < count; i++)
            {
                range.Add(list[index + i]);
            }
            range.Sort(comparer);
            Copy(range, 0, list, index, count);
        }
    }

    private static void Copy<T>(IList<T> sourceList, int sourceIndex,
        IList<T> destinationList, int destinationIndex, int count)
    {
        for (int i = 0; i < count; i++)
        {
            destinationList[destinationIndex + i] = sourceList[sourceIndex + i];
        }
    }
}

用法:

class Foo
{
    public int Bar;

    public Foo(int bar) { this.Bar = bar; }
}

void TestSort()
{
    IList<int> ints = new List<int>() { 1, 4, 5, 3, 2 };
    IList<Foo> foos = new List<Foo>()
    {
        new Foo(1),
        new Foo(4),
        new Foo(5),
        new Foo(3),
        new Foo(2),
    };

    ints.Sort();
    foos.Sort((x, y) => Comparer<int>.Default.Compare(x.Bar, y.Bar));
}

这里的想法是利用底层的功能 List<T> 尽可能处理排序。再次强调,大多数 IList<T> 我见过的实现都使用这个。如果底层集合是不同类型,则回退到创建新的实例 List<T> 使用输入列表中的元素,使用它进行排序,然后将结果复制回输入列表。即使输入列表没有实现,这也会起作用 IList 界面。

当我寻找原始帖子中描述的确切问题的解决方案时发现了这个线程。然而,没有一个答案完全符合我的情况。布罗迪的回答非常接近。这是我的情况和我找到的解决方案。

我有两个由 NHibernate 返回的相同类型的 IList,并将这两个 IList 合并为一个,因此需要排序。

就像 Brody 所说,我在对象(ReportFormat)上实现了 ICompare,它是我的 IList 的类型:

 public class FormatCcdeSorter:IComparer<ReportFormat>
    {
       public int Compare(ReportFormat x, ReportFormat y)
        {
           return x.FormatCode.CompareTo(y.FormatCode);
        }
    }

然后,我将合并的 IList 转换为相同类型的数组:

ReportFormat[] myReports = new ReportFormat[reports.Count]; //reports is the merged IList

然后对数组进行排序:

Array.Sort(myReports, new FormatCodeSorter());//sorting using custom comparer

由于一维数组实现了该接口 System.Collections.Generic.IList<T>, ,该数组可以像原始 IList 一样使用。

对于网格排序很有用,此方法根据属性名称对列表进行排序。如下示例所示。

    List<MeuTeste> temp = new List<MeuTeste>();

    temp.Add(new MeuTeste(2, "ramster", DateTime.Now));
    temp.Add(new MeuTeste(1, "ball", DateTime.Now));
    temp.Add(new MeuTeste(8, "gimm", DateTime.Now));
    temp.Add(new MeuTeste(3, "dies", DateTime.Now));
    temp.Add(new MeuTeste(9, "random", DateTime.Now));
    temp.Add(new MeuTeste(5, "call", DateTime.Now));
    temp.Add(new MeuTeste(6, "simple", DateTime.Now));
    temp.Add(new MeuTeste(7, "silver", DateTime.Now));
    temp.Add(new MeuTeste(4, "inn", DateTime.Now));

    SortList(ref temp, SortDirection.Ascending, "MyProperty");

    private void SortList<T>(
    ref List<T> lista
    , SortDirection sort
    , string propertyToOrder)
    {
        if (!string.IsNullOrEmpty(propertyToOrder)
        && lista != null
        && lista.Count > 0)
        {
            Type t = lista[0].GetType();

            if (sort == SortDirection.Ascending)
            {
                lista = lista.OrderBy(
                    a => t.InvokeMember(
                        propertyToOrder
                        , System.Reflection.BindingFlags.GetProperty
                        , null
                        , a
                        , null
                    )
                ).ToList();
            }
            else
            {
                lista = lista.OrderByDescending(
                    a => t.InvokeMember(
                        propertyToOrder
                        , System.Reflection.BindingFlags.GetProperty
                        , null
                        , a
                        , null
                    )
                ).ToList();
            }
        }
    }
try this  **USE ORDER BY** :

   public class Employee
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

 private static IList<Employee> GetItems()
        {
            List<Employee> lst = new List<Employee>();

            lst.Add(new Employee { Id = "1", Name = "Emp1" });
            lst.Add(new Employee { Id = "2", Name = "Emp2" });
            lst.Add(new Employee { Id = "7", Name = "Emp7" });
            lst.Add(new Employee { Id = "4", Name = "Emp4" });
            lst.Add(new Employee { Id = "5", Name = "Emp5" });
            lst.Add(new Employee { Id = "6", Name = "Emp6" });
            lst.Add(new Employee { Id = "3", Name = "Emp3" });

            return lst;
        }

**var lst = GetItems().AsEnumerable();

            var orderedLst = lst.OrderBy(t => t.Id).ToList();

            orderedLst.ForEach(emp => Console.WriteLine("Id - {0} Name -{1}", emp.Id, emp.Name));**

转换你的 IList 进入 List<T> 或其他一些通用集合,然后您可以使用轻松查询/排序它 System.Linq 命名空间(它将提供一堆扩展方法)

这是使用更强类型的示例。但不确定这是否一定是最好的方法。

static void Main(string[] args)
{
    IList list = new List<int>() { 1, 3, 2, 5, 4, 6, 9, 8, 7 };
    List<int> stronglyTypedList = new List<int>(Cast<int>(list));
    stronglyTypedList.Sort();
}

private static IEnumerable<T> Cast<T>(IEnumerable list)
{
    foreach (T item in list)
    {
        yield return item;
    }
}

Cast函数只是3.5自带的扩展方法的重新实现,写成普通的静态方法。不幸的是,它非常丑陋且冗长。

在VS2008中,当我单击服务引用并选择“配置服务引用”时,有一个选项可以选择客户端如何反序列化从服务返回的列表。

值得注意的是,我可以在 System.Array、System.Collections.ArrayList 和 System.Collections.Generic.List 之间进行选择

using System.Linq;

var yourList = SomeDAO.GetRandomThings();
yourList.ToList().Sort( (thing, randomThing) => thing.CompareThisProperty.CompareTo( randomThing.CompareThisProperty ) );

太漂亮了!贫民窟。

发现了一篇关于此的好帖子,我想分享一下。 在这里查看

基本上。

您可以创建以下类和 IComparer 类

public class Widget {
    public string Name = string.Empty;
    public int Size = 0;

    public Widget(string name, int size) {
    this.Name = name;
    this.Size = size;
}
}

public class WidgetNameSorter : IComparer<Widget> {
    public int Compare(Widget x, Widget y) {
        return x.Name.CompareTo(y.Name);
}
}

public class WidgetSizeSorter : IComparer<Widget> {
    public int Compare(Widget x, Widget y) {
    return x.Size.CompareTo(y.Size);
}
}

那么如果你有一个IList,你可以这样排序。

List<Widget> widgets = new List<Widget>();
widgets.Add(new Widget("Zeta", 6));
widgets.Add(new Widget("Beta", 3));
widgets.Add(new Widget("Alpha", 9));

widgets.Sort(new WidgetNameSorter());
widgets.Sort(new WidgetSizeSorter());

但请查看此网站以获取更多信息... 在这里查看

这是一个有效的解决方案吗?

        IList<string> ilist = new List<string>();
        ilist.Add("B");
        ilist.Add("A");
        ilist.Add("C");

        Console.WriteLine("IList");
        foreach (string val in ilist)
            Console.WriteLine(val);
        Console.WriteLine();

        List<string> list = (List<string>)ilist;
        list.Sort();
        Console.WriteLine("List");
        foreach (string val in list)
            Console.WriteLine(val);
        Console.WriteLine();

        list = null;

        Console.WriteLine("IList again");
        foreach (string val in ilist)
            Console.WriteLine(val);
        Console.WriteLine();

结果是:ilist b a c

列出A B C

再次iList a b c

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top