Linq Example 1 : A Simple Search

4:58 AM
Let's Say i have the following list of people's name:

"William H. Gates III"
"Warren Edward Buffet"
"Paul Gardner Allen"
"Sultan Hassanal Bolkiah"
"King Fahd Bin Abdulaziz Alsaud"
"Sheikh Zayed Bin Sultan Al Nahyan"
"Steven Anthony Ballmer"
"Amir Jaber Al-Ahmed Al-Jaber Al sabah"
"Phillip F. Anschutz"
"Michael Dell"

Now i want to search this name from a perticular word

In this example we will be searching for "Gates" Means our answer will be : "William H. Gates III"

Linq Qeury:

string[] strData = { "William H. Gates III", "Warren Edward Buffet", "Paul Gardner Allen", "Sultan Hassanal Bolkiah", "King Fahd Bin Abdulaziz Alsaud", "Sheikh Zayed Bin Sultan Al Nahyan", "Steven Anthony Ballmer", "Amir Jaber Al-Ahmed Al-Jaber Al sabah", "Phillip F. Anschutz", "Michael Dell" };
                
            var ans =
                from s in strData
                where s.Contains("Gates")
                select s;

            string strFound = "";
            foreach (var t in ans)
            {
                strFound += t.ToString() + Environment.NewLine ;
            }


Now After the above code the value of strFound will be : "William H. Gates III"


SameThing without linq can be done using following code:

string[] strData = { "William H. Gates III", "Warren Edward Buffet", "Paul Gardner Allen", "Sultan Hassanal Bolkiah", "King Fahd Bin Abdulaziz Alsaud", "Sheikh Zayed Bin Sultan Al Nahyan", "Steven Anthony Ballmer", "Amir Jaber Al-Ahmed Al-Jaber Al sabah", "Phillip F. Anschutz", "Michael Dell" };
                
            //without link
            strFound = "";
            foreach (string str in strData)
            {
                if (str.Contains("Gates"))
                {
                    strFound += str;
                }
            }



0 comments:

Post a Comment