2015-05-04 73 views
1

我有一個客戶端歷史記錄數據列表,裏面也有電話號碼。 我需要根據我的電話號碼列表來過濾歷史數據,這裏是我的代碼使用另一個值列表過濾linq

歷史課

public class MessengerHistory 
    { 
     public Int64 ClientId; 
     public string FirstName; 
     public string LastName; 
     public string ChartNumber; 
     public string PhoneNumber; 
     public string PetName; 
     public string Messagetext; 
    } 

List<string> phonenumber = List<string>{ "12345","45678","35487"} 

我得到消息歷史列表從API調用

var messageOverview = messengerAppWorkflow.GetMessageOverview(); 
    List<MessageHistroy> mHistory = messageOverview.messages.Select(item => item.clientPhone).ToList(); 

我想過濾mHistory值以返回與我的phonenumber列表匹配的歷史值,使用linq

+0

我更新了我的問題,這是錯的前 – user1845163

+0

對不起更新是正確的。這是複製粘貼錯誤 – user1845163

回答

2

你可以加入他們的行列:

var query = from msg in messengerAppWorkflow.GetMessageHistory() 
      join phone in phonenumber 
      on msg.PhoneNumber equals phone 
      select msg; 
List<MessageHistroy> mHistory = query.ToList(); 

另一less efficient的方法是使用Enumerable.Where + Contains

List<MessengerHistory> mHistory = messengerAppWorkflow.GetMessageHistory() 
    .Where(msg => phonenumber.Contains(msg.PhoneNumber)) 
    .ToList(): 
+0

感謝蒂姆其工作,我必須等待12分鐘才能接受。如何使用lambda實現相同? – user1845163

+1

當談到連接時,我不喜歡使用方法語法,但是使代碼變得深奧;)但需要注意的是,第一個片段中的查詢與使用一個班輪一樣有效。 –

-1

//這是你已經擁有

 List<MessengerHistory> reqMessengerHistoryList = new List<MessengerHistory>(); 

     List<string> phoneNumberList = new List<string> { "12345", "45678", "35487" }; 

//假設messengerHistoryList是您從api獲得的列表:

 List<MessengerHistory> messengerHistoryList = new List<MessengerHistory>(); 
     MessengerHistory messengerHistory1 = new MessengerHistory 
     { 
      ClientId = 123, 
      FirstName = "Rahul", 
      LastName = "Manhotra", 
      ChartNumber = "abc", 
      PhoneNumber = "12345", 
      PetName = "pqr", 
      Messagetext = "This is simple" 
     }; 
     MessengerHistory messengerHistory2 = new MessengerHistory 
     { 
      ClientId = 123, 
      FirstName = "Peter", 
      LastName = "stuv", 
      ChartNumber = "abc", 
      PhoneNumber = "34534", 
      PetName = "stu", 
      Messagetext = "This is hard" 
     }; 
     messengerHistoryList.Add(messengerHistory1); 
     messengerHistoryList.Add(messengerHistory2); 

//這是你需要做的:

 foreach (var item in messengerHistoryList) 
     { 
      if (phoneNumberList.Contains(item.PhoneNumber)) 
      { 
       requiredMessengerHistoryList.Add(item); 
      } 
     } 
     return requiredMessengerHistoryList; 
+1

@ simran..user期待LINQ版本的答案 –