SolvedPrivate

Help to improve simple LINQ statement.

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

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 19

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 19

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

744 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

11 Experts available now in Live!

Get 1:1 Help Now