LINQ副本(un)标记方法
本文关键字:方法 un 副本 LINQ | 更新日期: 2023-09-27 18:17:16
我已经阅读了一些检查dup的方法,但在这种情况下,我需要一个属性(IsDup),这很容易设置,但由于两个项目(相等的对象)都是IsDup,一旦两个项目中的一个被改变,就很难从两者中删除它。
这是我的示例代码,但我挣扎与组和计数的东西。基本上,我想查找任何组(基于相等)为1,这意味着它的伙伴(当前)被更改,它的IsDup现在为false,所以我需要将此项更改为false。
我认为这里的逻辑是合理的,我只是在LINQ方面挣扎
public class Test
{
public static void Main()
{
//current was a dup of the first item, which is why its set to true
var current = new CustOb(){ prop1 = "prop1C", prop2 = "prop2C", IsDup=true};
var list = new List<CustOb>();
list.Add(new CustOb(){ prop1 = "prop1A", prop2 = "prop2A", IsDup=true}); //was a dup with current
list.Add(new CustOb(){ prop1 = "prop1B", prop2 = "prop2B", IsDup=false});
list.Add(new CustOb(){ prop1 = "imadup", prop2 = "dup", IsDup=true}); //this is here to make sure a real dup isnt reset
list.Add(new CustOb(){ prop1 = "imadup", prop2 = "dup", IsDup=true}); //real dup
list.Add(current);
//code to be run on list item update
//reset to false and recheck now that its been changed
current.IsDup = false;
//check to see if the 'current' item is a dup with anything in the list
list.Where(o=>o.Equals(current)).Select(d => d.IsDup=true).ToArray();
//look for any partners that are orphaned from this
list.Where(o=> o.IsDup).GroupBy(x => x).Where(o=>o.Count() == 1).Select(o => o.IsDup = false);
list.ForEach(o=>
Console.WriteLine(o.prop1.ToString() + ", " + o.prop2.ToString() + ", " + o.IsDup.ToString())
);
}
}
public class CustOb
{
public string prop1 {get;set;}
public string prop2 {get;set;}
public bool IsDup {get;set;}
}
最后的结果是将所有列表项1的isdup设置为false
经过一番折腾,我终于能够让它与下面的LINQ一起工作了。Var的名字已经被改变了,因为它是在最终的应用程序中使用的。
//reset to false, and recheck for dups
selectedProductConnection.IsDup = false;
//check to see if the current item is a dup with anything in the list
var dups = ProductConnections.Where(o => !ReferenceEquals(o, selectedProductConnection) && o.GetDupHash() == selectedProductConnection.GetDupHash());
foreach (var pc in dups)
{
pc.IsDup = selectedProductConnection.IsDup = true;
}
//look for orphaned dup tags
var grp = new HashSet<int>(
ProductConnections.Where(o => o.IsDup)
.GroupBy(o => o.GetDupHash())
.Where(o => o.Count() == 1)
.Select(a => a.Key));
dups = ProductConnections.Where(x => grp.Contains(x.GetDupHash()));
foreach (var pc in dups)
{
pc.IsDup = false;
}
它可能可以稍微调整一下,但我对LINQ还是很陌生
我在我的对象上添加了一个自定义哈希,因为在我的实际用例中,它不比较整个对象,只比较某些字段。自定义散列就是
return Host.GetHashCode() ^ Product.GetHashCode() ^ Vendor.GetHashCode();