首页 > 解决方案 > 有没有更好的方法来编写这个 Duplicate ID Checker?

问题描述

首先,抱歉英语不好,这不是我的主要语言。其次,我不知道这是属于这里还是属于 Code Review。


基本上,此方法会询问List<Product>对象所在的 Inventory ( ) 以及ID的Int32值。 然后,它检查该ID 是否已存在于所述库存中,如果存在,则该函数搜索该 ID 可用的最低值。 这种方法的优点是不会浪费身份证号码,但我想听听一些关于如何改进它的意见...... Product
ProductInt32


if (inventory.Products.Where(x => x.ID == id).Any())
{
    idChanged = true;
    bool towardsNegative = true;

    while (inventory.Products.Where(x => x.ID == id).Any())
    {
        if(id < 0 && towardsNegative)
        {
            towardsNegative = false;
            id++;
        }

        if(towardsNegative)
        {
            id--;
        }
        else
        {
            id++;
        }
    }
}

标签: c#performancelinq

解决方案


请试试这个。

var data =  inventory.Products.GroupBy(x => x.ID).Where(x => x.Count() > 1).Select(x=>x.Key).ToList()

在此数据中,结果仅给出重复记录。

例如

public class Friend
{
  public int id { get; set; }
}
 List<Friend> lst = new List<Friend>();
            lst.Add(new Friend{ id = 1});
            lst.Add(new Friend { id = 1 });
            lst.Add(new Friend { id = 2 });
            lst.Add(new Friend { id = 3 });
            lst.Add(new Friend { id = 3 });
            lst.Add(new Friend { id = 4 });
var data1 = lst.GroupBy(x => x.id).Where(x => x.Count() > 1).Select(x=>x.Key).ToList();

推荐阅读