2017-08-23 40 views
0

我有一個字符串列表,我必須通過多次運行來嘗試減少重複。比較和組合一個類似的字符串列表

List <string> EventsList = BuildList.Distinct().ToList(); 

這消除確切副本,但偶爾會有一個包含確切的同一事件的不同變化的重複事件消息。

例如:

錯誤代碼[123]:失敗在[X]目錄中。

錯誤代碼[123]:在[Y]目錄中失敗。

這樣做的目的是,我可以再比較這些字符串,並拿出輸出:

錯誤代碼[123]:如果不按[X,Y]目錄。

由於不同的輸入總是在括號中,我創建了

string pattern = @"\[([^\]]+)"; 
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; 
Regex ConsolidatorRegex = new Regex(pattern, options); 
BuildList = EventsList; 
foreach (string singleEvent in BuildList) 
{ 
    ConsolidatorRegex.Replace(singleEvent, ""); 
} 

以爲我能然後比較字符串,並再次刪除重複。

但現在我卡住了。我想盡可能地保留按時間順序排列的事件的原始順序,但我無法想出最佳的解決方法。再次運行BuildList.Distinct().ToList();並不能幫助我捕捉(常爲多)去除較量,所以我可以將它們添加回。

我以爲我可以運行一個循環,做了String.Equals方法,並把全部命中到字典中則比較字典到EventsList,但我無法獲得循環的索引以創建字典密鑰。

有沒有更好的方法去解決這個問題我錯過了?

+0

大約有多少種不同的錯誤代碼? –

+0

@Rodrick約300我想?然而,並非所有事情都會拋出錯誤代碼,因爲有些事情只是簡單的事件,如「任務在[服務器名稱]上啓動」。我只是想提供一個例子,每個字符串有多個正則表達式匹配。 – Anatelo

回答

0

您可以按照提及的in the docs建立您的won比較器。

從文檔:

比較自定義數據類型,則需要實現這個接口 並提供自己的GetHashCode和等於該類型的方法。

請參閱the docs for that one

0

您可以使用LINQ GroupBy函數爲字符串分組。

var eventListGrouping = BuildList.GroupBy(eventString => ConsolidatorRegex.Replace(eventString, "")); 

然後你可以遍歷組:

foreach(var variation in eventListGrouping) 
{ 
    // Use variation.Key to find your 'template string' 
    // Iterate over variation to find all the string you want to combine 
    // You can reuse you regex to extract the values you want to combine 
    // Pay attention to adhere to the correct regex match count. 
} 

對於IGrouping接口的詳細信息,請參閱MSDN

0
var memo = new Dictionary<int, List<string>>(); 

var event_list = new List<string> 
    { 
     "Error code [123]: Failure in the [X] directory.", 
     "Error code [123]: Failure in the [Y] directory.", 
     "Error code [456]: Failure in the [Y] service.", 
    }; 

var pattern = new Regex(@"(code\s\[(?'code'\d+)\]).*\[(?'message'.*)\]"); 

foreach(var item in event_list) 
{  

    var match = pattern.Match(item); 
    var code = Int32.Parse(match.Groups["code"].Value); 
    var msg = match.Groups["message"].Value; 

    var messages = default(List<string>); 

    if(!memo.TryGetValue(code, out messages)) 
     memo.Add(code, messages = new List<string>()); 

    messages.Add(msg); 
} 

var directory_errors = from x in memo where x.Key == 123 select x; 

foreach(var error in directory_errors) 
    Console.WriteLine(string.Format("Error code [{0}]: Failure in the [{1}] directory", error.Key, string.Join(",", from err in error.Value select "'" + err + "'"))); 

的想法是,我們有我們使用的字典鍵入Dictionary<int, List<string>>,其中密鑰爲錯誤代碼(假定爲int),值爲List<string>

對於每個事件,我們使用正則表達式來提取代碼和消息,然後檢查字典以查看是否已經有與該代碼關聯的消息列表,如果是這樣,我們只需添加到列表中,但如果沒有,那麼我們創建列表並將它添加到字典中(使用錯誤代碼作爲關鍵字),然後我們將其添加到列表中。

Rextester Demo