2017-02-16 84 views
1

我有以下代碼:LINQ到實體 - 排序陣列

public List<OversizeElement> GetOversizeRegulations(List<string> states) 
    { 
     var tmpList = (from i in _db.States 
         where states.Any(p=>i.Name == p) 
         select new 
         { 
          StateID = i.ID, 
          StateName = i.Name, 
          StateShortName = i.ShortName 
         }).ToList(); 

所以,我請從「州」的變量對於所有狀態的附加信息。它的工作原理,但我需要得到相同的順序,如'狀態'變量。如何排序?它需要IComparer的對象,但我無法想象如何把它寫在我的情況

+0

如何'states'有序? –

+0

是從狀態不同然後tmplist? – lordkain

+0

@lordkain,不同 –

回答

2

如果你想在原來的排序,你可以這樣做:

public List<Destination> GetOversizeRegulations(List<string> states) 
{ 

     var tmpDictionary = (from i in _db.States 
          where states.Contains(i.Name) 
          select new 
             { 
             StateID = i.Id, 
             StateName = i.Name, 
             StateShortName = i.ShartName 
             } 
          ).ToDictionary(k => k.StateName, k => k); 

     var result = states 
        .Where(m=>tmpDictionary.ContainsKey(m)) 
        .Select(m => tmpDictionary[m]).ToList(); 


} 
+0

'_db.Destinations'從哪裏來? –

+0

@MatiasCicero對不起,這是你的Table(States)。我沒有編譯它,我認爲沒有任何其他的語法錯誤.. –

+0

@MatiasCicero我剛剛添加了最後的Where情況下狀態現在不存在於db –

0

枚舉states,而不是_db.States

var tmpList = states 
       .Select(s => _db.States.SingleOrDefault(st => st.Name == s)) 
       .Where(s => s != null) 
       .Select(new 
       { 
        StateID = s.ID, 
        StateName = s.Name, 
        StateShortName = s.ShortName 
       }); 
0

您可以OrderBy函數中使用IndexOf功能。假設在兩個列表中都有相同的id字段。讓我們在這件事上說,ID叫StateId

var tmpList = (from i in _db.States 
        where states.Any(p=>i.Name == p) 
        select new 
        { 
         StateID = i.ID, 
         StateName = i.Name, 
         StateShortName = i.ShortName 
        }).OrderBy(s => states.Select(x => x.StateId).IndexOf(s.StateId)).ToList();