2015-04-28 82 views
-2

我有一個list如下給出的硬編碼數據記錄。現在我想在這個清單上執行一些功能,這些功能會返回大多數高年級和初中的學生,以及一種可以返回第一卷的方法。所有學生和最後一種方法,其中FirstName="ali"返回學生。從c列表中獲取數據#

這是我當前的代碼:

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" });` 

建議和指導如何這裏着手讚賞。

+0

列表 objlist =新列表(); –

+0

你能澄清你的問題嗎?它是相當混亂.BTW由「20010」和「20011」你的意思是「2010」和「2011」我猜:) –

+1

嘗試自己製作這些方法,如果遇到問題,那麼你可以嘗試詢問StackOverflow。 – cubrr

回答

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

我認爲'FirstOrDefault'出現在錯誤的地方...... – crashmstr

+0

@crashmstr並且應該得到一個倒票? – Paparazzi

+0

它不會編譯,我不認爲OP會想辦法讓它工作,所以是的。但現在它已經修復了,我可以(也很容易)將我的失望記錄下來。 – crashmstr

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();