2017-09-02 75 views
0

我對於我的生活無法弄清楚這個LINQ查詢需要什麼。我在標準LINQ查詢上做得很好,但在這種情況下,我需要檢查集合中列表中項目的條件。Linq RemoveAll在集合內的列表中的謂詞條件

任務:

我需要刪除所有信息收集在他們的收件人列表中沒有包含某些字符串即「thiscompany.com」都在那裏句柄。

我嘗試到目前爲止:

// Remove internal messages 
var internalMessages = messages._results 
    .Where(x => x.recipients.All(y => y.handle.Contains("somecompany.com"))); 
messages._results = messages._results.Except(internalMessages).ToList(); 

據我瞭解這種方法會工作得很好,我只想需要實現平等Message對象上檢查,但因爲某些原因,我無法做到這一點。我知道LINQ必須有一種方法來執行一個基於收件人列表的子條件刪除所有消息的單行代碼,但我無法弄清楚從哪裏去。

消息對象:

public class Message 
{ 
    public _Links _links { get; set; } 
    public string id { get; set; } 
    public string type { get; set; } 
    public bool is_inbound { get; set; } 
    public float created_at { get; set; } 
    public string blurb { get; set; } 
    public Author author { get; set; } 
    public List<Recipient> recipients { get; set; } 
    public string body { get; set; } 
    public string text { get; set; } 
    public List<Attachment> attachments { get; set; } 
    public MessageMetadata metadata { get; set; } 
} 

收件人對象:

public class Recipient 
{ 
    public _Links _links { get; set; } 
    public string handle { get; set; } 
    public string role { get; set; } 
} 

回答

0

這將是簡單的:

message._result = messages._results 
.Where(x => x.recipients.Any(y => !y.handle.Contains("somecompany.com"))).ToList(); 

或者

messages._results 
.RemoveAll(x => !x.recipients.All(y => y.handle.Contains("somecompany.com"))); 
+0

如果我讀這正確不第一代碼片段說將所有結果的結果,所有收件人手柄與somecompany.com不符?只要他們不是全部somecompany.com,我可以擁有至少一個somecompany.com實例。我的理解是否正確? – tokyo0709

+0

我現在實際上現在我正在看它,你的第二個代碼片段基本上是我需要的,除了換掉Any for All。因爲如果我的理解正確,會刪除列出的所有收件人都包含somecompany.com的所有郵件。 – tokyo0709

+0

我已經更新了答案。第一個保留至少有一個句柄沒有「somecompany.com」的所有記錄。第二個刪除所有句柄都是「somecomany.com」的所有記錄。謝謝 –

0

cName是要排除的字符串。假設你將單獨採取的事實,cName可能爲空或空或空格護理,只是做:

var allMessages = messages._results; 
var externalMessages = allMessages 
    .Where(message => !message.recipients.All(to => to.handle.Contains(cName))) 
    .ToList();