排序接口列表 C#

我正在尝试按日期对接口列表进行排序,但我无法弄清楚。


var agencyList = new List<INewsItemBE>();


var item = new News1BE();

//add items

agencyList.Add(item)


var item = new News2BE();

//add items

agencyList.Add(item);

添加项目后,我想agencyList用这样的方式按日期排序,但我无法让它工作。


agencyList.Sort(delegate (News1BE c1, News1BE c2) { return c1.PublishDate.CompareTo(c2.PublishDate); });


agencyList.Sort(delegate (News1BE a, News1BE b) => a.PublishDate.CompareTo(b.PublishDate));

agencyList = agencyList.OrderBy(x => cant find anything at x.).ToList();


潇湘沐
浏览 129回答 2
2回答

皈依舞

试试 LINQ:using&nbsp;System.Linq; var&nbsp;ordered&nbsp;=&nbsp;agencyList.OrderBy(x&nbsp;=>&nbsp;x.PublishDate);或者如果你需要它降序:var&nbsp;orderedDesc&nbsp;=&nbsp;agencyList.OrderByDescending(x&nbsp;=>&nbsp;x.PublishDate);如果您再次需要原始变量中的列表,您可以调用.ToList():agencyList&nbsp;=&nbsp;agencyList.OrderBy(x&nbsp;=>&nbsp;x.PublishDate).ToList();如果 LINQ 不适合您(或者您希望获得最佳性能从而拒绝 LINQ 带来的开销),您可以使用.Sort您尝试的方法:agencyList.Sort((item1,&nbsp;item2)&nbsp;=>&nbsp;item1.PublishDate.CompareTo(item2.PublishDate));

富国沪深

您可以尝试使用 SortedList 代替 List,这样当您添加项目时它会自动排序。定义您的类/接口:interface INews1BE{&nbsp; &nbsp; DateTime PublishedDate { get; set; }}class News1BE : INews1BE{&nbsp; &nbsp; public DateTime PublishedDate { get; set; }}为 DateTime 定义比较器:class DateTimeAscendingComparer : IComparer<DateTime>{&nbsp; &nbsp; public int Compare(DateTime a, DateTime b)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return a.CompareTo(b);&nbsp; &nbsp; }}现在创建比较器和排序列表,将比较器传递给 SortedList 构造函数:var comparer = new DateTimeAscendingComparer();var sortedList = new SortedList<DateTime, INews1BE>(comparer);添加一些项目并检查结果:var item1 = new News1BE()&nbsp;{&nbsp; &nbsp; PublishedDate = DateTime.Now};var item2 = new News1BE(){&nbsp; &nbsp; PublishedDate = item1.PublishedDate.AddSeconds(-30)};sortedList.Add(item1.PublishedDate, item1);//item2 goes before item1sortedList.Add(item2.PublishedDate, item2);foreach(var x in sortedList){&nbsp; &nbsp; Console.WriteLine(x.Key);}您还可以通过 Value 访问您的对象:foreach (var x in sortedList){&nbsp; &nbsp; Console.WriteLine(x.Value.PublishedDate);}或者您可以迭代 Values 以立即访问您的 INews1BE 对象:foreach(var x in sortedList.Values){&nbsp; &nbsp; Console.WriteLine(x.PublishedDate);}实际上,如果您只关心升序,则不必为 DateTime 定义比较器 - 这是默认行为,因此您可以创建 SortedList 而无需将比较器传递给构造函数:var sortedList = new SortedList<DateTime, INews1BE>();但是,如果您需要降序,只需在比较时将DateTimea与 DateTime切换b:class DateTimeDescendingComparer : IComparer<DateTime>{&nbsp; &nbsp; public int Compare(DateTime a, DateTime b)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return b.CompareTo(a);&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP