Bigeyes
Bigeyes

Reputation: 1666

Can not deal with IEnumerable<int?> in generic

I have a method to concatenate strings provided by int?.

public string ConcatenateNumber(IEnumerable<int?> myList)
{
    return myList
        .Distinct()
        .Aggregate(
            new StringBuilder(), 
            (current, next) => current.Append("'").Append(next))
        .ToString()
        .Substring(1);
}

Now I want to do unit test.

[TestMethod]
public void InputIntegers_Should_Be_Concatenated_When_Consider_Distinct()
{
    var myList = CreateEnumerable(1, 2, 2, 3);
    var logic = new MainLogic();
    var result = logic.ConcatenateNumber(myList);
    Assert.AreEqual("1'2'3", result);
}

public IEnumerable<T> CreateEnumerable<T>(params T[] items)
{
    if (items == null)
        yield break;

    foreach (T mitem in items)
        yield return mitem;
}

However I have the compile error.

C#: Unknown method ConcatenateNumber(System.Collections.Generic.IEnumerable) of ....

I think it is caused by nullable integer int?. But I am not sure how to fix it.

Upvotes: 2

Views: 399

Answers (2)

Matthew Whited
Matthew Whited

Reputation: 22443

public void InputIntegers_Should_Be_Concatenated_When_Consider_Distinct()
{
    var myList = CreateEnumerable(1, 2, 2, 3);
    var logic = new MainLogic();
    var result = logic.ConcatenateNumber(myList);
}

public IEnumerable<T> CreateEnumerable<T>(params T[] items)
{
    return items ?? Enumerable.Empty<T>();
}

public class MainLogic
{

    public string ConcatenateNumber<T>(IEnumerable<T> myList)
    {
        // do this if you want to remove nulls
        return string.Join("'", myList.Where(i => i != null).Distinct()); 

        //return string.Join("'", myList.Distinct()); // otherwise do this
    }
}

Upvotes: 2

Shaun Luttin
Shaun Luttin

Reputation: 141542

Explicitly pass the type as a nullable int.

var myList = CreateEnumerable<int?>(1, 2, 2, 3);

For example:

using System;
using System.Linq;              
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var p = new Program();

        var list = p.CreateEnumerable<int?>(1, 2, 3, 4);
        p.DoWork(list);         
    }

    public void DoWork(IEnumerable<int?> enumerable)
    {
        enumerable.ToList().ForEach(x => 
        {
            Console.WriteLine(x);
        });
    }

    public IEnumerable<T> CreateEnumerable<T>(params T[] items)
    {
        if (items == null)
            yield break;

        foreach (T mitem in items)
            yield return mitem;
    }
}

Upvotes: 2

Related Questions