Int和Linq. ID [英] Int and Linq. Id
问题描述
您好,
我正在使用以下代码行生成ID:
Hello,
I am using the following code line to generate an Id:
Int32? newId = _users.Root.Elements("User").Select(a => Int32.Parse(a.Element("Id").Value)).Aggregate((Int32?)null, (x, i) => !x.HasValue || x.Value < i ? i : x);
_users是一个XDocument.如果没有找到用户,我希望newId为1;如果有用户,我希望所有ID的最大值加1.
我正在使用发布的代码:
所以以后我用:
_users is an XDocument. I would like newId to be 1 if no user is found or the Maximum value of all Ids plus 1 if there are are users.
I am using the code I am posting:
So later I use:
id == null ? 1 : newId + 1
我的问题是:
有没有办法没有最后一行.所以我想:
Int32 id =一些linq表达式,如果找不到用户,则返回1,如果有用户,则返回Max +1.
谢谢,
Miguel
My question is:
Is there a way to not have this last line. So I would like to:
Int32 id = Some linq expression that returns 1 if no user is found or Max + 1 if there are users.
Thanks,
Miguel
推荐答案
当ID为null(找不到用户)时,我使用GetValueOrDefault(1)获得1.我还修改了Agregate的功能以获取ID +1(所有ID的最大值+ 1).
I used GetValueOrDefault(1) to get 1 when Id is null (when no user is found). I also modified the function of the Agregate to get Id + 1 (Max value of all ids + 1).
XDocument _users = new XDocument(
new XElement("Root",
new XElement("User",
new XElement("Id", "1"),
new XElement("Id", "2"),
new XElement("Id", "3"),
new XElement("Id", "4"),
new XElement("Id", "5"),
new XElement("Id", "6"),
new XElement("Id", "7"),
new XElement("Id", "8"))));
var id = _users.Root.Elements("User").
Elements("Id").Select(e => int.Parse(e.Value)).Aggregate((int?)null, (x, i) => !x.HasValue || x.Value < i ? ++i : ++x).
GetValueOrDefault(1);
问候.
Regards.
这篇关于Int和Linq. ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!