Friday, 19 October 2012

Beginning .Net : Retrieve or Get only integer values from mixed values of string array or generic string List using LINQ with C# Examples and VB.Net Examples


This is a situations where you have an string array which contains some string element or values and some integer values and we want to parse that integer values from that List or array and retrieve only integer values. We can do with the help of LINQ. We can create an extension method of linq and achieve this.
This LINQ extension method is very useful.

Here is example for this.
In this example we take one List of string object. This List of string object contains both integer and string values.We parse that List of string object and get integer values from that.

In Vb.Net Example we need to add "Module" to create custom LINQ Extension method.


C# Examples :
static class LINQExtensions
{
    public static int? TryParseIntValues(this string item)
    {
        int tmp;
        bool success = int.TryParse(item, out tmp);
        return success ? (int?)tmp : (int?)null;
    }
}

protected void Page_Load(object sender, EventArgs e)
{

    var seq = new List<string> { "1", "apple", "3","4","5","computer" };
    var lstNums = (from item in seq select item.TryParseIntValues() ?? null);
    lstNums = (from t in lstNums where t.HasValue == true select t);

    Response.Write("<b>Numeric Values : </b></br>");
    foreach (object obj in lstNums)
    {
        Response.Write(obj.ToString() + "</br>");
        
    }
}

VB.Net Examples :

Public Module LINQExtensions

    <Runtime.CompilerServices.Extension()> _
    Public Function TryParseIntValues(ByVal source As String) As Nullable(Of Integer)
        Dim tmp As Integer
        Dim success As Boolean = Integer.TryParse(source, tmp)
        Return If(success, CType(tmp, System.Nullable(Of Integer)), CType(Nothing, System.Nullable(Of Integer)))
    End Function

End Module

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim seq As List(Of String) = New List(Of String)() From {"1", "apple", "3", "4", "5", "computer"}

    Dim lstNums = (From item In seq Select item.TryParseIntValues())

    lstNums = (From t In lstNums Where t.HasValue = True Select t)

    Response.Write("<b>Numeric Values : </b></br>")
    For Each obj As Object In lstNums
        Response.Write(obj.ToString() + "</br>")
    Next
End Sub

Output : 

This article is very useful for Beginning .Net.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



No comments:

Post a Comment

Post a Comment