简体   繁体   English

如何在LINQ .select中选择整数的最后一位?

[英]How can I select the last digit of an integer in a LINQ .select?

I have this LINQ select: 我有这个LINQ选择:

 var extendedPhrases = phrases
            .Select(x => new ExtendedPhrase()
            {
                Ajlpt = x.Ajlpt,
                Bjlpt = x.Bjlpt,
                Created = x.Created // an int?
            });

If I define: 如果我定义:

public int? CreatedLast { get; set; }

Then how can I populate that with the last digit of x.Created? 那我怎么用x.Created的最后一位填充呢?

If you are looking for the last digit of the Created property, the use the % operator like this: 如果要查找Created属性的最后一位 ,请使用%运算符,如下所示:

var extendedPhrases = phrases
        .Select(x => new ExtendedPhrase()
        {
            Ajlpt = x.Ajlpt,
            Bjlpt = x.Bjlpt,
            Created = x.Created,
            CreatedLast = x.Created % 10
        });

The first way to come to mind is to call .ToString().Last(): 首先想到的是调用.ToString()。Last():

var extendedPhrases = phrases
        .Select(x => new ExtendedPhrase()
        {
            Ajlpt = x.Ajlpt,
            Bjlpt = x.Bjlpt,
            Created = x.Created,
            CreatedLast = x.Created?.ToString().Last()
        });

If you aren't using the latest shiny C#, then null protection can be done with: 如果您不使用最新的闪亮C#,则可以使用以下方法进行空保护:

var extendedPhrases = phrases
        .Select(x => new ExtendedPhrase()
        {
            Ajlpt = x.Ajlpt,
            Bjlpt = x.Bjlpt,
            Created = x.Created,
            CreatedLast = x.Created.HasValue ? x.Created.ToString().Last() : null
        });

And some conversion back to an int? 并转换回int? left as an exercise to the reader. 留给读者练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM