LINQ Duplicate(un)标记方法

时间:2014-08-08 20:46:18

标签: c# linq

我已经阅读了几种方法来检查重复但是在这种情况下我需要一个易于设置的属性(IsDup),但由于两个项目(相同的对象)都是IsDup,因此很难删除一旦两个项目中的一个发生变化,它就会同时出现。

这是我的示例代码,但我正在努力与groupby和count计算。基本上我想查找任何组(基于相等)为1,意味着其伙伴(当前)已更改且其IsDup现在为假,因此我需要将此项更改为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

1 个答案:

答案 0 :(得分:1)

经过多次拧紧后,我能够使用以下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();