简体   繁体   中英

Call Method to LINQ in C#

Hello this is for my C# assignment

I am trying to write a program that will take user inputted data for several things IE first name, last name etc... put it into a list then print it out with the first letter of each word capitalized.

I have searched for two days trying to figure this out but have had no luck. I have the data going to the list and can display it no problem but I am having an issue figuring out how to call the method inside the LINQ statement.

i have to use UppercaseWords method in my program. What I can't get is how to call it into the LINQ

** this is in my Main method ***

// convert first letter of each word to uppercase var MakeCap = from values in PersonInfoS let value = values.ToUpper() select value;

** This is below Main **

 public static string UppercaseWords(string Value)
    {


        char[] array = Value.ToCharArray();

        if (array.Length >= 1)
        {
            if (char.IsLower(array[0]))
            {
                array[0] = char.ToUpper(array[0]);
            }
        }

        for (int i = 1; i < array.Length; i++)
        {
            if (array[i - 1] == ' ')
            {
                if (char.IsLower(array[i]))
                {
                    array[i] = char.ToUpper(array[i]);
                }
            }
        }


        return new string(array);
    } //   end UppercaseWords

I have tried a lot of different ways to get it to work. I am posting the only version that it doesn't crash on even though there is no link to UppercaseWords in there.

also i have it all in one class right now. I did try to using two classes but that didn't help me any.

if anyone can just give me a push in the right direction i'd appreciate it because I am out of ideas.

Thank you in advance for your time

Simply change this:

let value = values.ToUpper()

To this:

let value = UppercaseWords(values)

As an aside, you don't need to use the let clause in this case even though you can. so your whole query can become:

var makeCap = from values in PersonInfoS       
              select UppercaseWords(values);

This is with method syntax which is simpler in this case.

var cappedWords = PersonInfoS.Select(UppercaseWords);

Also, you should work on that UppercaseWords method. My advice would be to first split the string like this: value.Split(' ') so you have an array of the words. Then you can iterate over those words, get the first char, ToUpper them, and after everything Join(' ') them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM