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
you have to fix FetchExtras method
result
You could
yield return
the item containing the latestDateFrom
amongst those items that fulfill your condition:.MaxBy()
is available from .Net 6.MaxBy( * )
can be replaced with e.g..OrderByDescending( * ).First()
.