2013-06-13 48 views
2

我需要通過爲字符串類型排序用字符串

例如相對於一個List<string>排序比較列表 : 我有一個包含以下項目的列表。

Kaboki 
kriiki 
Kale 
Kutta 
Kiki 
Kicki 
Krishna 
Kseaki 

搜索關鍵詞的ki我要以這種方式使用關鍵字列表項,匹配字符串開頭的字符串有應該是第一,並具有在其他匹配字符串串排序位置必須在最後

這裏是我當前的代碼

public static List<string> GetLocations(string prefixText) 
    { 
     try 
     { 
      DataTable dtlocs = (DataTable) HttpContext.Current.Session["locations"]; 
      var dValue = from row in dtlocs.AsEnumerable() 
         where row.Field<string>("Location_Name").ToLower().Contains(prefixText.ToLower()) 
         select row.Field<string>("Location_Name"); 

      var results = dValue.OrderBy(s => s.IndexOf(prefixText, StringComparison.Ordinal)); 
      var str = new List<string>(results.ToList()); 

      if (!str.Any()) 
       str.Add("No locations found"); 
      return str; 
     } 
     catch (Exception) 
     { 
      var str = new List<string> {"No locations found"}; 
      return str; 
     } 
    } 

在這裏我能夠得到的第一個匹配的值到頂部,但不能剩下的值進行排序

和我有另一個問題。有一個詞King Koti,我正在搜索Ko這個詞先來。我認爲這是因爲,字符串有兩個子字符串,其中一個子字符串以匹配的字開頭。

我可以使匹配的字母大膽?

回答

1

我認爲這應該工作:

list = (from str in list 
     let idx = str.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) 
     let change = idx != 0 ? idx : int.MinValue 
     orderby change 
     select str).ToList(); 
1

您可以使用LINQ的OrderBy的組合和IndexOf方法:

var input = ... 
var search = "ki"; 
var results = input.Select(Value => new { Value, Index = s.IndexOf(search, StringComparison.InvariantCultureIgnoreCase) }) 
        .Where(pair => pair.Index >= 0) 
        .OrderBy(pair => pair.Index) 
        .Select(pair => pair.Value); 

或者在查詢語法:

var results = 
    from s in input 
    let i = s.IndexOf(search, StringComparison.InvariantCultureIgnoreCase) 
    where i >= 0 
    orderby i 
    select s; 
+1

我認爲這將會把輸入沒有ocurrence在結果頂部的搜索。 – Rawling

+0

@Rawling謝謝,現在應該修復 –

2

OrderBy訂單falsetrue

var result = list.OrderBy(s => !s.StartsWith("ki", StringComparison.OrdinalIgnoreCase)) 
       .ThenBy(s => !s.ToLower().Contains("ki")); 
+0

這不適用於我 –

+0

@KrishnaThota:你能發佈你的預期結果嗎? –

3
var res = list.OrderBy(y=> !y.StartsWith("Ki", StringComparison.OrdinalIgnoreCase)) 
       .ThenBy(x => x)