如何按字段对列表进行排序

26

大家好

我有一个对象列表

我的对象像这样

Product = "iPhone"; 
Category = "SmartPhone";

Product = "HP"; 
Category = "PC";

Product = "HTC"; 
Category = "SmartPhone";

然后我将每个对象插入到我的测试中,就像这样

List<Myobject> MyList = new List<Myobject>();

现在,我需要按类别对MyList进行排序。

因为我希望我的列表首先显示智能手机类别,然后是其他类别。

3个回答

38

你可以使用List.Sort

l.Sort((p, q) => p.Category.CompareTo(q.Category));

与 LINQ 的 OrderBy 相比,这种方法的优点是可以原地对列表进行排序,而不是生成一个 IOrderedEnumerable<T> 然后再将其转换为 List<T>


在我看来,这是一个缺点,因为我认为“有序列表”是对原始数据的一种视图。因此,我更喜欢让原始列表保持不变。 - Frederik Gheysels
2
@FrederikGheysels 幸运的是,你可以选择 :-) - xanatos

21

请查看LINQ的OrderBy扩展方法。

MyList.OrderBy (p => p.Category);
如果您需要一种更复杂的方式来对类别进行排序,您可以创建一个实现IComparer接口的类,并在其中实现您的排序逻辑。
        public class SmartphonesFirst : IComparer<Product>
        {
            const string Smartphone = "Smartphone";

            public int Compare( Product x, Product y )
            {
                if( x.Category == Smartphone && y.Category != Smartphone )
                {
                    return -1;
                }
                if( y.Category == Smartphone && x.Category != Smartphone )
                {
                    return 1;
                }
                else
                {
                    return Comparer<String>.Default.Compare (x.Category, y.Category);
                }
            }
        }

你可以不使用LINQ来完成它:

            var l = new List<Product> ();
            l.Add (new Product ()
            {
                Name = "Omnia 7",
                Category = "Smartphone"
            });

            l.Add (new Product ()
            {
                Name = "Mercedes",
                Category = "Car"
            });

            l.Add (new Product ()
            {
                Name = "HTC",
                Category = "Smartphone"
            });

            l.Add (new Product ()
            {
                Name = "AMD",
                Category = "CPU"
            });

            l.Sort (new SmartphonesFirst ());

            foreach( var p in l )
            {
                Console.WriteLine (String.Format ("{0} : {1}", p.Category, p.Name));
            }

或者使用LINQ:

            var l = new List<Product> ();
            l.Add (new Product ()
            {
                Name = "Omnia 7",
                Category = "Smartphone"
            });

            l.Add (new Product ()
            {
                Name = "Mercedes",
                Category = "Car"
            });

            l.Add (new Product ()
            {
                Name = "HTC",
                Category = "Smartphone"
            });

            l.Add (new Product ()
            {
                Name = "AMD",
                Category = "CPU"
            });

            var sorted = l.OrderBy (p => p, new SmartphonesFirst ());

            foreach ( var p in sorted )
            {
                Console.WriteLine (String.Format ("{0} : {1}", p.Category, p.Name));
            }

6
您可以使用Sort方法和自定义比较,按类别(降序)和产品(升序)排序:
MyList.Sort((a, b) => {
  // compare b to a to get descending order
  int result = b.Category.CompareTo(a.Category);
  if (result == 0) {
    // if categories are the same, sort by product
    result = a.Product.CompareTo(b.Product);
  }
  return result;
});

如果您想单独列出智能手机并按升序排序:
MyList.Sort((a, b) => {
  int result = (a.Category == "SmartPhone" ? 0 : 1) - (b.Category == "SmartPhone" ? 0 : 1);
  if (result == 0) {
    result = a.Category.CompareTo(b.Category);
    if (result == 0) {
      result = a.Product.CompareTo(b.Product);
    }
  }
  return result;
});

当类别字段相等时,进一步按产品字段排序,加1。 - Alex Essilfie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接