SolvedPrivate

Help to improve simple LINQ statement.

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

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

Suggested Solutions

Title # Comments Views Activity
C# Comparing String Arrays. 5 57
SqlDependency to get update from sql to my c# app 2 61
Cant save 3D 4 22
Object Oriented Programming, C#, referencing, scoping. 13 69
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

791 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