c# - 有没有更好的方法来编写这个 Duplicate ID Checker?
问题描述
首先,抱歉英语不好,这不是我的主要语言。其次,我不知道这是属于这里还是属于 Code Review。
基本上,此方法会询问
List<Product>
对象所在的 Inventory ( ) 以及ID的Int32
值。
然后,它检查该ID 是否已存在于所述库存中,如果存在,则该函数搜索该 ID 可用的最低值。
这种方法的优点是不会浪费身份证号码,但我想听听一些关于如何改进它的意见......
Product
Product
Int32
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++;
}
}
}
解决方案
请试试这个。
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();
推荐阅读
- ios - RxSwift:立即交付第一个项目,消除后续项目
- swift - Swift 中的实体组件
- javascript - 为什么当我尝试获取数据时 NPS Api 返回 503
- r - 如何在 ggplot 中的 y 轴(断轴)上创建一个中断?
- python - 熊猫尝试改用 .loc[row_indexer,col_indexer] = value
- java - 使用 Selenium WebDriver (Java) 上传本地图像
- string - 球拍编程:如何在 2 个空格字符后添加新行?
- android - 如何在更改布局管理器时为 Recycler-View 设置动画
- python - 通过第一个字母查找列表项并存储在两个不同的列表中并组合成字典
- javascript - 是否可以在服务人员中每分钟调用一个函数