2012-08-11 43 views
0

我需要搜索集合中的一個詞的開頭。執行集合中的搜索與音譯

簡單集合{伊萬·史密斯,安東尼·克拉克,麥克筱田}

當用戶輸入「S」,我需要出示{伊萬·史密斯,麥克筱田}

這種方法應該工作,但它不」噸。

 private void SortFriends(object sender, TextChangedEventArgs e) { 
      var text = (sender as WatermarkTextBox).Text; 
      if (text != string.Empty) { 
      text = text.ToLowerInvariant(); 
      var translatedColl = FriendCollectionTranslated.Where(i => i.FirstName.StartsWith(text) || i.LastName.StartsWith(text) || 
               i.FirstNameT.StartsWith(text) || 
               i.LastNameT.StartsWith(text)); 

      var newCollection = ((App)App.Current).CollectionFriends.Where(i => translatedColl.First(n => n.Uid == i.Uid) != null); 

      friendsBox.ItemsSource = newCollection; 
      } 
      else friendsBox.ItemsSource = ((App)App.Current).CollectionFriends; 
     } 
    public class HumanTranslated { 
      public string Uid { get; set; } 
      public string FirstName { get; set; } 
      public string LastName { get; set; } 
      public string FirstNameT { get; set; }//Translit 
      public string LastNameT { get; set; }//Translit 
      public bool IsChecked { get; set; } 
     } 
private void PrepareCollection()//Ретранслируем наши данные для быстрого поиска 
    { 
     foreach (var t in ((App)App.Current).CollectionFriends) { 
     var item = new HumanTranslated { 
      Uid = t.Uid, 
      LastNameT = ToTranslit(t.LastName.ToLowerInvariant()), 
      FirstNameT = ToTranslit(t.FirstName.ToLowerInvariant()), 
      FirstName = t.FirstName.ToLowerInvariant(), 
      LastName = t.LastName.ToLowerInvariant() 
     }; 
     FriendCollectionTranslated.Add(item); 
     } 
    } 
public class Human { 
      public string Uid { get; set; } 
      public string FirstName { get; set; } 
      public string LastName { get; set; } 
      public bool IsChecked { get; set; } 
     } 
+0

什麼是'收集朋友'和'FriendCollectionTranslated'..通過提出好問題來幫助自己... – Anirudha 2012-08-11 14:21:11

回答

2

將相同的.ToLowerInvariant()調用添加到您的lambda表達式中的每個成員。

var translatedColl = FriendCollectionTranslated.Where(
         i => i.FirstName.ToLowerInvariant().StartsWith(text) || 
          i.LastName.ToLowerInvariant().StartsWith(text) || 
          i.FirstNameT.ToLowerInvariant().StartsWith(text) || 
          i.LastNameT.ToLowerInvariant().StartsWith(text)); 

更妙的是,使用StringComparison.InvariantCultureIgnoreCase

var translatedColl = FriendCollectionTranslated.Where(
       i => i.FirstName.StartsWith(text,StringComparison.InvariantCultureIgnoreCase) || 
        i.LastName.StartsWith(text,StringComparison.InvariantCultureIgnoreCase) || 
        i.FirstNameT.StartsWith(text,StringComparison.InvariantCultureIgnoreCase) || 
        i.LastNameT.StartsWith(text, StringComparison.InvariantCultureIgnoreCase)); 

然後你可以刪除你的文字變量ToLowerInvariant()調用。

+0

請參閱編輯,它已經在更低。 – SevenDays 2012-08-11 14:26:32

+0

您編輯的答案有效!謝謝。 – SevenDays 2012-08-11 14:32:56