我有一個包含重復項的串列。
List<string> filterList = new List<string>()
{
"postpone", "access", "success", "postpone", "success"
};
我得到了postpone, access, success使用的輸出
List<string> filter = filterList.Distinct().ToList();
string a = string.Join(",", filter.Select(a => a).ToArray());
Console.WriteLine(a);
我看過其他例子,他們可以groupby用來獲取最新的元素,因為他們有其他專案,比如 ID 等。現在我只有字串,我怎樣才能獲得串列中的最新專案access, postpone, success?有什么建議嗎?
uj5u.com熱心網友回復:
一種方法是將原始集合中專案的索引與 GroupBy 一起使用。例如,
var lastDistinct = filterList.Select((x,index)=> new {Value=x,Index=index})
.GroupBy(x=>x.Value)
.Select(x=> x.Last())
.OrderBy(x=>x.Index)
.Select(x=>x.Value);
var result = string.Join(",",lastDistinct);
輸出
access,postpone,success
uj5u.com熱心網友回復:
您的輸入串列只是字串型別,因此使用 groupBy 并沒有真正添加任何內容。如果您考慮您的代碼,您的第一行為您提供了不同的串列,您只會丟失不同的專案,因為您在第 2 行執行了 string.join。您需要做的就是在加入之前添加一行:
List<string> filter = filterList.Distinct().ToList();
string last = filter.LastOrDefault();
string a = string.Join(",", filter.Select(a => a).ToArray());
Console.WriteLine(a);
我想你可以讓你的代碼更簡潔,因為你在呼叫 string.Join 時既不需要 .Select(a => a) 也不需要 .ToArray() 。
如果您有一個類/結構/記錄/元組專案串列,您可能希望按特定鍵(或多個鍵)進行分組,而不是對整個事物使用 Distinct(),則將使用 GroupBy。GroupBy 非常有用,您應該了解這一點,以及 ToDictionary 和 ToLookup LINQ 幫助程式功能。
uj5u.com熱心網友回復:
OrderedDictionary 就是這樣做的。您所要做的就是使用“如果它在字典中,將其洗掉。添加它”的邏輯將您的專案添加到其中。OrderedDictionary 通過洗掉先前添加的并重新添加它來保留添加順序,從而跳轉到字典的末尾
var d = new OrderedDictionary();
filterList.ForEach(x => { if(d.Contains(x)) d.Remove(x); d[x] = null; });
你d.Keys現在是一個字串串列
access
postpone
success
OrderedDictionary 在Collections.Specialized命名空間中
如果您想要將鍵作為 CSV,您可以使用Cast將它們從物件轉換為字串
var s = string.Join(",", d.Keys.Cast<string>());
uj5u.com熱心網友回復:
那么為什么不應該回傳第一次出現的“推遲”呢?因為在后面的序列中,您會再次看到同一個詞“推遲”。為什么要回傳第一次出現的“訪問”?因為在后面的序列中你不會再看到這個詞了。
所以:如果序列的其余部分沒有這個詞,則回傳一個詞。
這在 LINQ 中很容易,使用遞回,但效率不高:對于每個單詞,您必須檢查序列的其余部分以查看該單詞是否在其余部分中。
記住找到單詞的最高索引會更有效。
作為擴展方法。如果您不熟悉擴展方法,請參閱擴展方法揭秘。
private static IEnumerable<T> FindLastOccurences<T>(this IEnumerable<T> source)
{
return FindLastOccurrences<T>(source, null);
}
private static IEnumerable<T> FindLastOccurences<T>(this IEnumerable<T> source,
IEqualityComparer<T> comparer)
{
// TODO: check source not null
if (comparer == null) comparer = EqualityComparer<T>.Default;
Dictionary<T, int> dictionary = new Dictionary<T, int>(comparer);
int index = 0;
foreach (T item in source)
{
// did we already see this T? = is this in the dictionary
if (dictionary.TryGetValue(item, out int highestIndex))
{
// we already saw it at index highestIndex.
dictionary[item] = index;
}
else
{
// it is not in the dictionary, we never saw this item.
dictionary.Add(item, index);
}
index;
}
// return the keys after sorting by value (which contains the highest index)
return dictionay.OrderBy(keyValuePair => keyValuePair.Value)
.Select(keyValuePair => keyValuePair.Key);
}
所以對于源序列中的每個專案,我們檢查它是否在字典中。如果沒有,我們將該專案作為鍵添加到字典中。該值是索引。
如果它已經在字典中,那么該值是我們之前找到該專案的最高索引。顯然當前索引更高,所以我們替換字典中的值。
最后我們將字典中的鍵值對按升序排列,只回傳鍵值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/367380.html
