按字段排序列表(C#)
我喜欢上课:
class SortNode { public Int32 m_valRating = 0; public SortNode(Int32 valRating) { this.m_valRating = valRating; } }
和一些列表refSortNodeList
:
List refSortNodeList = new List(); Random refRandom = new Random(); for (int i = 0; i < 100; ++i) { refSortNodeList.Add(new SortNode(refRandom.Next(-10, 30))); } foreach (var varSortNode in refSortNodeList) { Console.WriteLine("SortNode rating is {0}", varSortNode.m_valRating); }
如何通过m_valRating
字段轻松地对我的refSortNodeList
进行排序? 或者我可能需要使用另一个List
类?
list.Sort((x,y) => x.m_valRating.CompareTo(y.m_valRating));
到位:
refSortNodeList.Sort( (x, y) => x == null ? (y == null ? 0 : -1) : (y == null ? 1 : x.m_valRating.CompareTo(y.m_valRating)) );
创建一个新的枚举:
var newEnum = refSortNodeList.OrderBy(x => x.m_valRating);
创建新列表:
var newList = refSortNodeList.OrderBy(x => x.m_valRating).ToList();
就地是最快和最有效的内存,但如果你想保留旧列表也没有好处。
下一个比最后一个快,并在结果出现时给出结果,但你必须重新进行排序再次使用它,在这种情况下,第三个是要去的那个。
使用Linq命令。
var mySortedList = refSortNodeList.OrderBy(x => x.m_valRating);
这是一个真实的实例,我从数据库中提取列表,但它是完全相同的概念。
vendorProducts = (from vp in db.COMPANIES_VND_PRODUCTS join p in db.CT_CT_INV_CLASSES on vp.CLASS_ID equals p.CLASS_ID join m in db.CT_CT_MODALITY_CODES on vp.MODALITY_ID equals m.MODALITY_ID where vp.COMPANY_ID == companyId select new ProductTypeModality { Active = p.ACTIVE.Equals("Y") ? true : false, BioMedImaging = p.BIOMED_IMAGING, Code = p.CLASS_CODE, Description = p.DESCRIPTION, Id = p.CLASS_ID, PricingMargin = p.PRICING_MARGIN, ModalityCode = m.MODALITY_CODE, ModalityId = m.MODALITY_ID, VendorId = companyId }).OrderBy(x => x.Code).ToList();
实现IComparable
使用linq很容易:
var newlist = refSortNodeList.sort( n => n.m_valRating );
您可以使用Linq进行基本排序:
refSortNodeList.OrderBy(n => n.m_valRating);
如果您需要更复杂的排序,您需要实现IComparable
以使用内置排序。
试试这个:
refSortNodeList.Sort(new delgate(SortNode x, SortNode y) { return x.CompareTo(y); } );
List refSortNodeList = new List (); Random refRandom = new Random (); for (int i = 0; i < 100; ++i) { refSortNodeList.Add (new SortNode (refRandom.Next (-10, 30))); } // Use this (Linq) if you're using .NET 3.5 or above. var sortedList = refSortNodeList.OrderBy (node => node.m_valRating); foreach (var varSortNode in sortedList) { Console.WriteLine ("SortNode rating is {0}", varSortNode.m_valRating); } // Use this otherwise (eg .NET 2.0) refSortNodeList.Sort ( delegate (SortNode n1, SortNode n2) { return n1.m_valRating.CompareTo (n2.m_valRating); } ); foreach (var varSortNode in refSortNodeList) { Console.WriteLine ("SortNode rating is {0}", varSortNode.m_valRating); }