简体   繁体   中英

Finding Max Value of an nvarchar column in sql server 2012 using LINQ

I have a table full of serial numbers of a product, the datatype is nvachar, i have entries like 1001, 1002, 1003, abc001, efg002, 1004, def222 . I have to return the max value of the valid numeric numbers in the column, in this case output should be 1004.

This SQL Query is working

select top 1
  cast(SerialNo as integer)
from [InvSerialItemDetails]
where isNumeric(SerialNo) = 1
Order by cast(SerialNo as integer) desc

I have to do the same in LINQ . But there is no isNumeric function in LINQ. How to get the same output in LINQ in VB language

如果您使用Linq to Entities还有一个比较隐蔽IsNumeric Linq中的功能。

Her is an example in VB.Net. I just used a List of strings and the LINQ expression will grab the highest number in the List.

    Dim nvarcharNubers As List(Of String) = New List(Of String)

    nvarcharNubers.Add("abc1007")
    nvarcharNubers.Add("1002")
    nvarcharNubers.Add("1003")
    nvarcharNubers.Add("1004")
    nvarcharNubers.Add("2000fg")
    nvarcharNubers.Add("999")

    Dim TopNumberOnly = From i In nvarcharNubers
                      Where IsNumeric(i)
                      Select i = Integer.Parse(i)
                      Order By i Descending
                      Take 1

or if you wanted to use Lambda statements then:

    Dim TopNumberOnly = nvarcharNubers _
                        .Where(Function(w) IsNumeric(w)) _
                        .Select(Function(s) Integer.Parse(s)) _
                        .OrderByDescending(Function(o) o) _
                        .Take(1)

If you are sure that your database field will only contain numeric value than you can always use max for nvarchar field. See below example :

var serials = new List<SerialObject>();

// Add AlphaNumeric value to the list
serials.Add(new SerialObject()
                {
                    Id = "1",
                    Serial = "aa10a1"
                });

// Add AlphaNumeric value to the list
serials.Add(new SerialObject()
{
    Id = "2",
    Serial = "cc11da"
});

// Add Numeric values to the list
for (int i = 0; i < 5; i++)
{
    serials.Add(new SerialObject()
                    {
                        Id = i.ToString(),
                        Serial = (1000 + i).ToString()
                    });
}

// Fetch max numeric from list using regular expression
var regex = new Regex("^[0-9]*$");

var numbers = serials.Where(a => regex.IsMatch(a.Serial)).Select(a => a.Serial).ToList();

var max = numbers.Max(a => a);

Serial Object Class

public class SerialObject
    {
        public string Id { get; set; }

        public string Serial { get; set; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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