我有一個字串串列,其中包含例如以下專案:
0$1, 0$2, 0$5, 1$1, 1$8
如果已經存在,我的意愿是用 $1 洗掉其他專案。在那個例子中,預期的輸出是:
0$1, 0$2, 0$5, 1$8
有沒有更簡潔的方法來實作這一點,使用 LINQ 或其他任何東西,而不是做這樣的事情?
For Each str As String In ddlElecDBFilter.SelectedItemsList
Dim currentString As String = str
'DO A FOR EACH LOOP on the other elements (starting from the current index 1 and delete them
Next
先感謝您
uj5u.com熱心網友回復:
不確定是否有“更干凈”的方法來做到這一點:
Dim input As String = "0$1, 0$2, 0$5, 1$1, 1$8"
Dim uniqueValues As New List(Of String)
input.Split(", ".ToCharArray, StringSplitOptions.RemoveEmptyEntries) _
.Where(Function(x) x.Contains("$")) _
.Select(Function(y) New KeyValuePair(Of String, String)(y.Substring(y.IndexOf("$")), y)) _
.ToList() _
.ForEach(Sub(pair)
If Not uniqueValues.Any(Function(x) x.EndsWith(pair.Key)) Then
uniqueValues.Add(pair.Value)
End If
End Sub)
Dim output As String = String.Join(", ", uniqueValues)
uj5u.com熱心網友回復:
既然你說 C# 是可以接受的,那么我的答案是 C#。如果您在翻譯到 VB.Net 時遇到問題,我可以添加。
我不會說 LINQ 更干凈,但它很短。當你需要積累物品時,Aggregate就是使用的方法。當您需要在處理時保持某種型別的狀態時,Aggregate使用ValueTuple(或其他一些容器)可以讓您在處理時保留一個值。
如果ss包含您的List<string>,ans則將包含已處理的字串:
var ans = ss.Select(s => s.Split(", ")
.Aggregate((ans: Enumerable.Empty<string>(), seen: false), // accumulate result in ans, track whether $1 has been seen
(ans_seen, item) => ans_seen.seen
? (item.EndsWith("$1") ? ans_seen : (ans_seen.ans.Append(item), ans_seen.seen))
: (ans_seen.ans.Append(item), item.EndsWith("$1"))
)
.ans.Join(", ")) // string extension method that encapsulates String.Join
.ToList();
這使用了一個明顯的字串擴展方法來封裝String.Join.
我會說最好創建一個使用回圈的函式并僅使用 LINQ 進行List處理:
public static class StringExt {
public static string KeepOnlyFirstDollarOne(this string s) {
var seen = false;
var resultList = new List<string>();
foreach (var item in s.Split(", ")) {
if (seen) {
if (!item.EndsWith("$1"))
resultList.Add(item);
}
else {
resultList.Add(item);
seen = item.EndsWith("$1");
}
}
return String.Join(", ", resultList);
}
}
那么得到答案就這么簡單:
var ans = ss.Select(s => s.KeepOnlyFirstDollarOne()).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388406.html
下一篇:LINQ查詢表
