有没有更好的方法来编码此重复ID检查器?

时间:2019-03-07 01:03:02

标签: c# performance linq

首先,对不起英语,对不起,这不是我的主要语言。其次,我不知道它是否属于此处或在Code Review中。


基本上,此方法要求对象所在的清单(List<Product>)和Int32 ID的Product值。
然后,它检查在所述清单中是否已经存在Product ID,如果存在,该函数将搜索可用于该ID的最低Int32值。

这种方法的优点是不会浪费ID号,但我想听听一些有关如何改进它的意见。

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++;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

请尝试这个。

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();
相关问题