从不完全重复的对象列表中删除多余的(重复的)对象



我在C#中有一个对象列表,这些对象具有多个属性(价格、颜色、描述和日期已添加,但NOT是唯一ID(。最终目标是过滤列表-如果其中两个对象的价格和颜色相同,我们会检查描述中是否包含50%以上的匹配单词(但不相同,因为它们是免费输入的(。此外,有时dateAdded可以是空的,因此优选地,如果存在2〃;"重复";我们保留带有日期添加的

所以

  1. [100美元,红色,"漂亮的棉质衬衫","2020年10月29日"]

  1. 〔100美元,红色,"棉质衬衫","01/01/0001"〕

被视为重复,需要从列表中删除没有日期的。

我知道使用linq的可以实现简单的重复消除

var noDups = myList.GroupBy(x => x.Id).Select(x => x.First()).ToList();

但如果我在我的情况下进行分组,我不知道以后如何检查描述/日期。

此外,我知道这可以通过多个foreach循环和临时列表来解决,但我担心这样会变得太复杂

我尝试的是使用相同的列表——动态删除元素,但在两个循环结束后,元素就丢失了。

foreach (var prop in listOfProducts)
{
foreach (var secondProp in listOfProducts.Where(x => x.ListingID != prop.ListingID).ToList())
{
if (prop.Price == secondProp.Price && prop.Color == secondProp.Color )
{

var propSplitDesc = prop.Description.Split().ToList();
var secondPropSplitDesc = secondProp.Description.Split().ToList();
var descLength = propSplitDesc.Count > secondPropSplitDesc.Count
? propSplitDesc.Count
: secondPropSplitDesc.Count;
var wordsMatching = propSplitDesc.Intersect(secondPropSplitDesc).ToList();
if (wordsMatching.Count >= (double)descLength / 2)
{
finalProp.ComaprableProperties.Remove(prop.DateAdded == DateTime.MinValue
? prop
: secondProp);
}
}
}
}

有没有什么不太复杂的东西可以做,或者linq可以以某种方式使用?

我还没有测试过它,但我认为以下内容应该适用于您。然后由你决定它是否更容易阅读:

var noDups = myList.GroupBy(x => new { x.Color, x.Price })
.SelectMany(group => 
{
var candidates = group.ToList();
return candidates.Where(x => candidates
.Where(y => y != x) // Don't compare against itself
.All(y =>
// Other candidate does not match by words
!HasMoreThanHalfMatchingWords(x, y)
// ... or this one does have a proper date
|| x.DateAdded != DateTime.MinValue));
});
// In some other place...
bool HasMoreThanHalfMatchingWords(string desc1, string desc2)
{
// Logic to compare if the strings contain more than 50% matching words
}

关于定义的注意事项

我认为你对";重复";。考虑以下示例:

项目A

  • 描述:";那只棕色的狐狸跳过了那只懒狗
  • 添加日期:2020年10月29日

项目B

  • 描述";棕色的狐狸跳了起来
  • 添加日期:2020年10月29日

项目C

  • 描述:";跳过那只懒狗">
  • 添加日期:01/01/0001

哪些项目被认为是重复的,哪些项目最终会出现在最终列表中?

A和B共有50%的单词。A和C也一样。

你是否应该只保留A,即使B和C看起来不同,这意味着你正在丢失没有重复的项目?

你应该同时保留A和B吗?A,因为它有一个";dateAdded";是C和B的重复,因为。。。它不是一个";重复";所以你应该保留其中一个?

最新更新