SolvedPrivate

Help to improve simple LINQ statement.

Posted on 2014-11-28
5
42 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

696 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