2015-09-16 43 views
0

我可以在Linq中使用OrderBy()。Then()對具有重複值的實體的字符串屬性。 爲例Linq OrderBy然後重複項

public class Test 
{ 
    public Guid Id{get;set;} 
    public string Name{get;set;} 
    public DateTime Date{get;set;} 
} 

我要訂購基於名稱測試實體列表(即可以複製),然後,命令日期的結果。

例如

public class Test 
{ 
    public Guid Id { get; set; } 
    public string Name { get; set; } 
    public DateTime Date { get; set; } 
} 

public class TestLinq 
{ 
    private IList<Test> list; 

    public TestLinq() 
    { 
     var dateTime = DateTime.Now; 
     list = new List<Test> 
     { 
      new Test {Id = Guid.NewGuid(), Name = "Masoud", Date = dateTime}, 
      new Test {Id = Guid.NewGuid(), Name = "Bahrami", Date = dateTime}, 
      new Test {Id = Guid.NewGuid(), Name = "Ali", Date = DateTime.Now}, 
      new Test {Id = Guid.NewGuid(), Name = "hasan", Date = DateTime.Now}, 
      new Test {Id = Guid.NewGuid(), Name = "Masoud", Date = DateTime.Now}, 
      new Test {Id = Guid.NewGuid(), Name = "Bahrami", Date = DateTime.Now}, 
     }; 
    } 

    public List<Test> Get(string name) 
    { 
     return list.OrderBy(test => test.Name).ThenBy(test => test.Date).ToList(); 
    } 
} 
+1

是的,你可以,你面臨的問題是什麼? –

+0

@ Rahul Singh,當運行查詢我發生了這個錯誤「一個列已被指定不止一次按順序排列。order by必須是唯一的」 –

+0

@MasoudBahrami你可以發佈整個查詢,我懷疑你指定了Name列按子句排序兩次? –

回答

0

也許我可以得到它的權利,但你爲什麼有這樣的字符串名稱參數?你沒有使用它。或者你想獲得這個名字的所有記錄,然後按名稱和日期對它們進行排序? 如果你想這個話,我覺得代碼會爲你工作:

list.Where(t=> t.Name == name).OrderBy(t => t.Name).ThenBy(t => t.Date).ToList(); 

另一個問題是,你設置DateTime.Now無處不在,ThenBy標準是不是在這種情況下工作。

糾正我,如果我錯了某處。我會很樂意幫助

+0

非常感謝。是的名稱是用於過濾器,並且在某些情況下名稱和日期都是等值。 –

0

請不要猶豫,使用此方法。

list.OrderBy(test => test.Name).ThenBy(test => test.Date).ThenBy(test => test.Id).ToList(); 
+0

嗨。非常感謝,好吧,我很好地測試它,但我不確定,你的解決方案可以解決它。 –