gpt4 book ai didi

c# - 删除字典中的重复项

转载 作者:太空狗 更新时间:2023-10-30 01:23:59 25 4
gpt4 key购买 nike

如果我有这样的字典,

Dictionary<int, string> roadNames = new Dictionary<int, string>();

roadNames.Add(1, "Rosedale Rd");
roadNames.Add(2, "Transmere Rd");
roadNames.Add(3, "Rosedale Rd");
roadNames.Add(4, "Rosedale Rd");
roadNames.Add(5, "Rosedale Rd");
roadNames.Add(6, "Rosedale Rd");
roadNames.Add(7, "Rosedale Rd");
roadNames.Add(8, "Brown Rd");
roadNames.Add(9, "Harold Rd");

是否有 LINQ 解决方案来删除彼此相邻的重复项。我追求的结果是一个包含这个的列表,

Rosedale Rd
Transmere Rd
Rosedale Rd
Brown Rd
Harold Rd

请注意,Rosedale Rd 仍两次出现在列表中。我们的想法是删除彼此相邻的重复项,在本例中,我们要删除第 4、5、6 和 7 项。

项目 1 不在项目 3 旁边,因此不会被删除。

更新:

不用担心字典没有被排序。有序列表的解决方案就可以了。我可以处理订单。即

List<string> roadNames = new List<string>()
{
"Rosedale Rd",
"Transmere Rd",
// etc
};

最佳答案

假设您使用的是排序字典(或任何其他排序结构),则有两种选择。

利用响应式扩展

如果您利用 Reactive Extensions,这将非常简单来自微软(每个人都应该!):

roadNames.Values // remove if a list instead
.ToObservable()
.DistinctUntilChanged()
.ToList();

您可以更改最终的 ToList()ToEnumerable()如果你愿意的话。

返回:

Rosedale Rd 
Transmere Rd
Rosedale Rd
Brown Rd
Harold Rd

使用扩展方法

您可以使用 GroupAdjacent扩展方法如下:

roadNames.Values // remove if a list instead
.GroupAdjacent((x,y) => x == y)
.Select(x => x.First());

扩展方法:

public static IEnumerable<IEnumerable<T>> GroupAdjacent<T>(
this IEnumerable<T> source, Func<T, T, bool> adjacent)
{
var g = new List<T>();
foreach (var x in source)
{
if (g.Count != 0 && !adjacent(g.Last(), x))
{
yield return g;
g = new List<T>();
}
g.Add(x);
}
yield return g;
}

关于c# - 删除字典中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10629393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com