0

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?

3
  • Are you sure there is a match for the exact string returned by ToShortDateString? Commented Nov 28, 2012 at 17:39
  • 2
    Could be a locale issue with the date formatting. Commented Nov 28, 2012 at 17:39
  • If you can refactor to use a DateTime for ETA instead of a string, comparisons will be easier. Commented Nov 28, 2012 at 17:40

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.