SolvedPrivate

Help to improve simple LINQ statement.

Posted on 2014-11-28
5
44 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

717 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