从c#

时间:2015-04-28 15:05:22

标签: c# .net

我有一个list如下所示,带有硬编码数据记录。现在我想在这个列表上执行一些功能,这些功能将返回大多数高级和初级学生以及一个返回滚动号的方法。所有学生,最后一种方法,让学生返回FirstName="ali"

这是我目前的代码:

 List<StnRecDAL> objlist = new List<StnRecDAL>();

 objlist.Add(new StnRecDAL { RollNo = 1, FirsName = "ali", LastName = "helo", ClassName = "a", SessionYear = "2002" });
 objlist.Add(new StnRecDAL { RollNo = 2, FirsName = "ali", LastName = "helo", ClassName = "b", SessionYear = "2003" });
 objlist.Add(new StnRecDAL { RollNo = 3, FirsName = "ali", LastName = "helo", ClassName = "c", SessionYear = "2004" });
 objlist.Add(new StnRecDAL { RollNo = 4, FirsName = "ali", LastName = "helo", ClassName = "d", SessionYear = "2005" });
 objlist.Add(new StnRecDAL { RollNo = 5, FirsName = "ali", LastName = "helo", ClassName = "e", SessionYear = "2006" });
 objlist.Add(new StnRecDAL { RollNo = 6, FirsName = "ali", LastName = "helo", ClassName = "f", SessionYear = "2007" });
 objlist.Add(new StnRecDAL { RollNo = 7, FirsName = "ali", LastName = "helo", ClassName = "g", SessionYear = "2008" });
 objlist.Add(new StnRecDAL { RollNo = 8, FirsName = "ali", LastName = "helo", ClassName = "h", SessionYear = "2009" });
 objlist.Add(new StnRecDAL { RollNo = 9, FirsName = "ali", LastName = "helo", ClassName = "i", SessionYear = "20010" });
 objlist.Add(new StnRecDAL { RollNo = 10,FirsName = "ali", LastName = "helo", ClassName = "j", SessionYear = "20011" });`

有关如何进行此处的建议和指导表示赞赏。

2 个答案:

答案 0 :(得分:0)

var first = objlist.OrderBy(x => x.SessionYear).FirstOrDefault();

答案 1 :(得分:0)

LINQ扩展可以在这里为您提供帮助。您可能需要阅读LINQ和lambda表达式。

# The ordering works below with your examples, but you might want to consider entering the dates correctly ("20011" vs "2011") and as a different datatype.
var first = objlist.OrderBy(x=>Int32.Parse(x.SessionYear)).First();
var last = objlist.OrderBy(x=>Int32.Parse(x.SessionYear)).Last();

# A list of integers
var allRollnos = objlist.OrderBy(x=>Int32.Parse(x.SessionYear)).Select(x=>x.RollNo).ToList();

# A list of StnRecDAL objects  
var studentsCalledAli = objlist.Where(x=>x.FirstName=="ali").ToList();