SolvedPrivate

Help to improve simple LINQ statement.

Posted on 2014-11-28
5
38 Views
Last Modified: 2016-02-15
Hi Guys, I'm a total newbie to c# and need help to improve/correct LINQ statements. I wrote two simple methods to learn and understand LINQ statement, when I give it the correct value lists everything works 100% but when I don't give expected values it fails. Is there a better way to complete my task without writing try catch statements?

Please can you help, code and comments.

Code:

 List<int> numbers = new List<int>()
{
    // Below value works fine
    //1, 4, 5, 9, 11, 15, 20, 27, 34, 55

    // Below values return a error
    1, 3, 5, 7, 9, 11, 13, 15, 17, 19
};
// the following method must return the first event number - as suggested by it's name
int firstValue = Program.GetFirstEvenValue(numbers);
Console.WriteLine("First Number: " + firstValue);

List<string> strings = new List<string>()
{
    // Below value works fine
    "John", "Jane", "Sarah", "Pete", "Anna"

    // Below values return a error
    //"Jhn", "Jn", "Srh", "Pt"
};
// the following method must return the first name which contains an 'a'
string strValue = Program.GetSingleStringValue(strings);
Console.WriteLine("Single String: " + strValue);

Open in new window

Respective methods:

public static int GetFirstEvenValue(List<int> numbers)
{
    // RETURN THE FIRST EVEN NUMBER IN THE SEQUENCE
    int first = numbers.Where(x => x % 2 == 0).First();
    return first;
}

public static string GetSingleStringValue(List<string> stringList)
{
    // THE OUTPUT MUST RENDER THE FIRST ITEM THAT CONTAINS AN 'a' INSIDE OF IT
    string first = stringList.Where(x => x.IndexOf("a") != -1).Single();
    return first;
}

Open in new window

0
Comment
Question by:DickSwart
  • 3
  • 2
5 Comments
 
LVL 20

Expert Comment

by:Daniel Van Der Werken
ID: 40471618
Use .FirstOrDefault() and .SingleOrDefault()

       
     // the following method must return the first event number - as suggested by it's name
            int firstValue = Program.GetFirstEvenValue(numbers);
            Console.WriteLine("First Number: " + firstValue);

            List<string> strings = new List<string>()
            {
                // Below value works fine
                //"John", "Jane", "Sarah", "Pete", "Anna"

                // Below values return a error
                "Jhn", "Jn", "Srh", "Pt"
            };

            // the following method must return the first name which contains an 'a'
            string strValue = Program.GetSingleStringValue(strings);
            Console.WriteLine("Single String: " + strValue);

Open in new window

0
 
LVL 20

Accepted Solution

by:
Daniel Van Der Werken earned 500 total points
ID: 40471619
Sorry. I added the incorrect section. Here is the sample using FirstOrDefault and SingleOrDefault:

   
    public static int GetFirstEvenValue(List<int> numbers)
        {
            // RETURN THE FIRST EVEN NUMBER IN THE SEQUENCE
            int first = numbers.Where(x => x % 2 == 0).FirstOrDefault();
            return first;
        }

        public static string GetSingleStringValue(List<string> stringList)
        {
            // THE OUTPUT MUST RENDER THE FIRST ITEM THAT CONTAINS AN 'a' INSIDE OF IT
            string first = stringList.Where(x => x.IndexOf("a") != -1).SingleOrDefault();
            return first;
        }

Open in new window

0
 
LVL 20

Assisted Solution

by:Daniel Van Der Werken
Daniel Van Der Werken earned 500 total points
ID: 40471622
Here is an article on working with the difference between Single() and SingleOrDefault() and First() and FirstOrDefault() too:

http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
0
 

Author Comment

by:DickSwart
ID: 40472091
Hi Dan7el, Just so help with the .SingleOrDefault(). In my example list there are multiple names that contains the letter "a" and therefore an Exception Error: InvalidOperationException: Sequence contains more than one element.

How will I handle this then, as I will not always be able to control what is in my list?
0
 

Author Comment

by:DickSwart
ID: 40472093
List<string> strings = new List<string>()
{
    "John", "Jane", "Sarah", "Pete", "Anna"
};
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now