-1

The task is: A sequence of positive integer values integerList is given. Get sequence of string representations of only odd integerList values and sort in ascending order. This is my code:

public static IEnumerable<string> Task5(IEnumerable<int> integerList)
    {
        var result = from item in integerList
                     where item % 2 != 0
                     orderby item descending
                     select item;
        return result.Cast<string>();
    }

But I see this message every time, when try to start tests: System.InvalidCastException : Unable to cast object of type 'System.Int32' to type 'System.String'.

  • use `.ToString()` method instead of `Cast` – Ali Adlavaran Aug 24 '21 at 21:55
  • Does this answer your question? [IEnumerable to string delimited with commas?](https://stackoverflow.com/questions/3414263/ienumerable-to-string-delimited-with-commas) – MicroVirus Aug 24 '21 at 21:57
  • 1
    Since this looks like homework, I'd recommend taking this opportunity to learn how to read error messages and use a debugger. If you're using Visual Studio, you can [attach a debugger](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger?view=vs-2019) and run the code, and it should show you exactly where the problem is: the `result.Cast()` expression. Then you can look up (click on and press F12) the `Enumerable.Cast` method and see why it might throw that exception. – Joe Sewell Aug 24 '21 at 22:00
  • does your assignment mention how to handle any duplicate [odd] numbers? – coding.monkey Aug 24 '21 at 22:07
  • Also, every answer here, including the original code posted, is sorting the values in **descending** order but the description of the task clearly says **ascending** order. ```descending``` should be probably be removed from the code – coding.monkey Aug 24 '21 at 22:08

4 Answers4

2

Don't cast, use .ToString() instead

  public static IEnumerable<string> Task5(IEnumerable<int> integerList)
    {
        var result = from item in integerList
                     where item % 2 != 0
                     orderby item descending
                     select item.ToString();
        return result;
    }
Laphaze
  • 278
  • 1
  • 6
0

result is a collection of integers, not strings. And you can't directly cast integers to strings. But you can call .ToString() on them. So you can use something like .Select() to project them into a new collection using that operation. For example:

return result.Select(r => r.ToString());

Though it's probably worth examining whether this method should return a collection of strings when the source data is integers. Why not just return the collection of integers instead? Seems cleaner:

public static IEnumerable<int> Task5(IEnumerable<int> integerList)
{
    return from item in integerList
           where item % 2 != 0
           orderby item descending
           select item;
}

It's difficult to say for certain because "Task5" doesn't exactly describe the operation being performed in any detail. But the method is receiving integers and it looks like the intent is to simply modify that collection, so it makes sense that it would return integers.

Then it would be up to the consuming code to convert them to strings if it needs strings for some purpose outside the scope of this method.

David
  • 208,112
  • 36
  • 198
  • 279
0
  public static List<string> Task5(IEnumerable<int> integerList)
    {
        var result = from item in integerList
                     where item % 2 != 0
                     orderby item ascending
                     select item;
        List<int> mylist = result.ToList();
        return mylist.ConvertAll(x => x.ToString());
    }


    public static IEnumerable<string> Task5(IEnumerable<int> integerList)
    {
        var result = from item in integerList
                     where item % 2 != 0
                     orderby item ascending
                     select item.ToString();
        return result;
    }
0

This definitely sounds like a homework assignment to me as well... if so, perhaps the name Task5 is a requirement of the assignment. If not, then as @David suggested, the method name should reflect what operation the method performs (e.g. FindOddNumbersAscending())

Here's what I believe is the correct implementation based on the description of the assignment and also mirroring the feedback above:

public static IEnumerable<string> FindOddNumbersAscending(IEnumerable<int> integerList)
{
    return from item in integerList
           where item % 2 != 0
           orderby item
           select item.ToString();
}

This can be taken slightly farther to protect against null input as well as removing any duplicates (if that's desirable; note the switch to fluent syntax rather than query syntax for removing duplicates):

public static IEnumerable<string> FindOddNumbersAscending(IEnumerable<int> integerList)
{
    return integerList is null
        ? Enumerable.Empty<string>()
        : integerList
            .Where(item => item % 2 != 0)
            .Distinct()
            .OrderBy(item => item)
            .Select(item => item.ToString());
}

coding.monkey
  • 206
  • 1
  • 6
  • I should also note that I share the same concern @David had about transforming the numbers to strings. That definitely feels like something consuming code should be concerned with and not a side effect of this operation. That said, it all depends on the parameters of the assignment/task. – coding.monkey Aug 24 '21 at 22:29