Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ递增ID_C#_Linq_Asp.net Web Api_Lambda - Fatal编程技术网

C# 使用LINQ递增ID

C# 使用LINQ递增ID,c#,linq,asp.net-web-api,lambda,C#,Linq,Asp.net Web Api,Lambda,每当我从前端添加新对象时,id=0。在WebApi层中,我试图找到对象列表中存在的最大ID,然后将下一个ID分配给新对象。下面的代码没有正确增加ID List<Event> events = eventVal.Where(e => e != null).ToList(); int eventMaxID = events.Max(e => e.id); events.Where(e => e.id == 0) .Select((e, ixc) => new

每当我从前端添加新对象时,id=0。在WebApi层中,我试图找到对象列表中存在的最大ID,然后将下一个ID分配给新对象。下面的代码没有正确增加ID

List<Event> events = eventVal.Where(e => e != null).ToList();
int eventMaxID = events.Max(e => e.id);

events.Where(e => e.id == 0)
  .Select((e, ixc) => new { id = eventMaxID + 1, Iter = eventMaxID + 1 })
  .ToList();
List events=eventVal.Where(e=>e!=null).ToList();
int eventMaxID=events.Max(e=>e.id);
其中(e=>e.id==0)
.Select((e,ixc)=>new{id=eventMaxID+1,Iter=eventMaxID+1})
.ToList();
我不确定如何使用Select方法的第二个参数


任何帮助都将不胜感激!谢谢。

在您使用的第二种选择形式中,ixc是集合中项目的索引。你需要添加它以及之前的max Id。这样你就不必担心分配给Iter了(看起来你只是把它用作某种计数器),所以我把它删除了

var autoIncrementedEvents = events.Where(e => e.id == 0)
  .Select((e, ixc) => 
  {
     e.id = eventMaxId + 1 + ixc;
     return e;
  })
  .ToList();
请注意,编写代码的方式将丢弃此Linq语句的结果。你会想把它分配给我上面做过的事情


我不打算评论这在网络环境(竞争条件、重复ID等)中作为整体方法的有效性。理想情况下,您的数据存储应该分配Id。

您的示例代码正确吗?您对
events.Select(e=>e.id==0)
的调用看起来像是
events.Where(e=>e.id==0)
是的,您是对的。您能详细说明一下“没有工作”吗。很难说清楚你到底想完成什么,那是行不通的。我正在尝试将事件中的ID列更新为下一个递增的ID。
List newEvent=events.Where(e=>e.ID==0)。选择((e,ixc)=>new{ID=ixc+eventMaxID+1+e.ID})给出错误“无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic”。List@rds80Linq用于选择和转换。您现在已将
事件
转换为匿名类型。@rds80这是因为您使用了新的{}这会创建一个匿名对象。我只是从您的原始问题复制。如果您需要处理事件,请参阅我更新的代码段,如果可能,它肯定应该由数据库完成。设想这样一种情况,即在不同线程上同时有两个调用进入您的API。您将无法协调分配到f正确输入Id