[英]What am i doing wrong with my C# looping
好,所以我有2個清單
List<string> playlists
List<string> sync
假設播放列表的內容是三個字符串
{"more and you", "and us", "more"}
同步的內容是這個
{"more and you-20120312", "more and you-20120314", "more and you-20120313", "and us-20120313", "and us-20120314", "more-20120314", "more-20120313", "more-20120312"}
基本上,我想做的是遍歷播放列表中的所有循環,找到相關的同步並打印出來,它們必須為3,否則我想為它們着色不同..所以這是到目前為止的代碼
StringBuilder sb = new StringBuilder();
sb.Append("<h2>Playlist Information</h2>");
foreach (string play in playlists)
{
int counter = 0;
foreach (string s in sync)
{
if (s.StartsWith(play))
{
sb.Append("<p class=\"good\">" + s + "</p>");
counter++;
}
}
}
所以我希望最終的html看起來像這樣
<h2>Playlist Information</h2>
<p class=\"good\">more and you-20120312</p>
<p class=\"good\">more and you-20120313</p>
<p class=\"good\">more and you-20120314</p>
<p class=\"bad\">and us-20120313</p>
<p class=\"bad\">and us-20120314</p>
<p class=\"good\">more-20120312</p>
<p class=\"good\">more-20120313</p>
<p class=\"good\">more-20120314</p>
對於不滿足至少3個項目的項目不利...關於如何使用我的代碼實現此目標的任何想法
實現此目標非常容易-只需在檢查過程中建立另一個列表而不是計數器,然后檢查“內部列表”的大小即可。 我稱之為currentSyncSet:
static void Main(string[] args)
{
List<string> playlists = new List<string>(){"more and you", "and us", "more"};
List<string> sync = new List<string>() { "more and you-20120312", "more and you-20120314", "more and you-20120313", "and us-20120313", "and us-20120314", "more-20120314", "more-20120313", "more-20120312" };
StringBuilder sb = new StringBuilder();
sb.Append("<h2>Playlist Information</h2>\r\n");
HashSet<string> finalSyncResult = new HashSet<string>();
foreach (string play in playlists)
{
List<string> currentSyncSet = new List<string>();
foreach (string s in sync)
{
if (s.StartsWith(play))
{
currentSyncSet.Add(s);
}
}
foreach (var syncset in currentSyncSet)
{
if (currentSyncSet.Count < 3)
{
finalSyncResult.Add("<p class=\"bad\">" + syncset + "</p>");
}
else
{
finalSyncResult.Add("<p class=\"good\">" + syncset + "</p>");
}
}
}
foreach (var result in finalSyncResult)
{
sb.Append(result + "\r\n");
}
Console.WriteLine(sb.ToString());
Console.ReadKey();
}
輸出為:
<h2>Playlist Information</h2>
<p class="good">more and you-20120312</p>
<p class="good">more and you-20120314</p>
<p class="good">more and you-20120313</p>
<p class="bad">and us-20120313</p>
<p class="bad">and us-20120314</p>
<p class="good">more-20120314</p>
<p class="good">more-20120313</p>
<p class="good">more-20120312</p>
問候
更新1:對不起,上一次,我忘記了,您不想重復條目-因此,我在此解決方案中添加了HashSet。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.