skip to Main Content

I am writing a Unit test where in i am passing array of two records and i want to send it to a method
which can filter the records and pass only a single record but i have tried to use FirstOrDefault but then it is throwing compile time error

here is my code

[Test]
        public void Test()
        {
            var first = new Extra
            {
                Code = "P1",
                Cost= 100,
                DateFrom = DateTime.Parse("01 March 2022")
            };
            var second = new Extra
            {
                Code = "P3",
                Cost= 120,
                DateFrom = DateTime.Parse("01 April 2022")
            };
            var totalData= new[]
            {
                first,
                second
            };


            var value= GetExtraHandler.FetchExtras(totalData, DateTime.Parse("02 April 2022"));

            Assert.Equal(value, new[] { second });

Here is method which get called in GetExtraHandler

    public static IEnumerable<Extra> FetchExtras(Extra[] lvl, DateTime idate)
    {

        var data= lvl.Where(x => x.DateFrom < idate).FirstOrDefault();
        return data;
    }

So from this code when i build i am getting compile time error that method expects IEnumerable return type so if i use firstordefault it is throwing error.
I want a way so that if multiple records is less than datefrom i.e 02 April 2022 and in array which is passed is 01 April and 01 March then only 01 April record should get fetched.
Thanks for help in advance.

2

Answers


  1. you have to fix FetchExtras method

    public static IEnumerable<Extra> FetchExtras(Extra[] lvl, DateTime idate)
    {
    return lvl.Where(x => x.DateFrom < idate).OrderByDescending(x=> x.DateFrom).Take(1);
    }
    

    result

    [
      {
        "Code": "P3",
        "Cost": 120,
        "DateFrom": "2022-04-01T00:00:00"
      }
    ]
    
    Login or Signup to reply.
  2. You could yield return the item containing the latest DateFrom amongst those items that fulfill your condition:

    public static IEnumerable<Extra> FetchExtras(Extra[] lvl, DateTime idate)
    {
        yield return lvl.Where(x => x.DateFrom < idate).MaxBy(x => x.DateFrom);
    }
    

    .MaxBy() is available from .Net 6.
    MaxBy( * ) can be replaced with e.g. .OrderByDescending( * ).First().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search