Somebody
Somebody

Reputation: 2779

Generic List Find using lambda expression in c#

I have this code:

List<Visibility> ListVisibility = new List<Visibility>();
    public class Visibility
    {
        public int ShpNo;
        public int QtyShp;
        public int NumPallets;
        public string ETA;            
    }

Visibility item = ListVisibility.Find(VisibItem => VisibItem.ETA == e.Day.Date.ToShortDateString());

But the above Find is not returning any Item, when there is an item that matches that condition.

What could be wrong here?

Upvotes: 0

Views: 4250

Answers (3)

Preston Guillot
Preston Guillot

Reputation: 6714

Occam's razor: Your assumption that there is an item that matches your condition is incorrect.

You can verify that the method works with a simple test (this uses NUnit).

[Test]
public void TestFind()
{
     var etaValue = DateTime.Now.Date.ToShortDateString();
     var visibilities = new List<Visibility> { new Visibility { ETA = etaValue } };
     var foundItem = visibilities.Find(x => x.ETA == etaValue);
     Assert.That(foundItem, Is.Not.Null);
}

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Most likely string match does not find a match. Change code to compare dates as Date portions of DateTime and it will have better chance to work.

item => DateTime.Parse(item.ETA).Date == e.Day.Date

Sample is assuming e.Day is DateTime. Also you may need to handle "item.ETA is not valid date/empty" case (i.e. by using DateTime.TryParse) to match original behavior.

Upvotes: 4

user7116
user7116

Reputation: 64068

Any number of things come to mind, but two that seem most likely:

  1. Is the string in Visibility.ETA trimmed of leading and trailing whitespace?

  2. Does the case of the string in Visibility.ETA match that of DateTime.ToShortDateString()?

If you change your condition to:

var date = e.Day.Date.ToShortDateString();
var vis = list.Find(
    v => String.Compare(v.ETA, date, StringComparison.OrdinalIgnoreCase) == 0);

Does it find the item you're looking for? If not you should consider whether or not you need to convert ETA to a DateTime.

Upvotes: 2

Related Questions