2016-09-28 94 views
-4

我有一些代碼,我希望可以重寫使用較短的代碼。 代碼工作正常,但我只是覺得代碼是環境。 這裏的一些基本的代碼 Dictionary dict = settings.files; OCCURENCES是一些屬性的對象,但一個名爲filename如何重寫我的循環使用較短的代碼

string fileNameShort; 
List<Common.Occurences> filteredList = new List<Occurences>(); 


//Lookup the right dictionary item for given filename in occurences 
for (int j = 0; j < settings.files.Count; j++) 
{ 
    if (occurences.FileName.StartsWith(dict.Keys.ElementAt(j))) 
    { 
     fileNameShort = dict.Keys.ElementAt(j); 

     if (dict[fileNameShort]) 
     { 
      filteredList.Add(occurences); 
      break; 
     } 
    } 
} 
+0

'dict'是什麼? –

+0

這是一本字典 – tony

+0

類型.......? –

回答

0
filteredList = (from entry in dict where entry.Value && occurence.FileName.StartsWith(entry.Key) select occurence).ToList(); 

也許這將有助於插入換行符的地方。

編輯:什麼打動我雖然是這個列表將包含相同的對象occurences只有重複,因爲這不取決於你的代碼索引j

+0

例如occurences.FileName =「babspaylink_cashit-bpti.1.log」,但settings.files包含在一個地方{babspaylink,true}其中鍵是bspspaylink且值爲true。 – tony

+0

因此,字典中的關鍵字有時會與出現的文件名不同 – tony

+0

@tony是的,但如果您有例如{babspaylink,true}和{babspay,true}在字典中,您將得到一個列表,其中有兩個相同的項目。該列表永遠不能包含兩個不同的項目,這就是爲什麼使用List是一個壞主意。 – Georg

0

這是一個開始

foreach(var j in settings.files.Where(x => occurences.Filename.StartsWith(x.Key)) 
{ 
    filteredList.Add(j); 
} 

但它遠不及你所需要的,因爲你的代碼是沒有意義的 - 我ATLEAST。

+0

public class Occurences
{ public string TimeStamp {get;組; } public string FileName {get;組; } 公共字符串Occurance {get;組; } public string ForeColor {get;組; } public string BackColor {get;組; } public int Index {get;組; } } – tony

+0

如果字典持有整個文件名,那麼爲什麼使用StartsWith()? – else

+0

另外;不需要字典。您可以使用使用列表並訪問FileName屬性 – else