How to apply check to select only simple strings and neglect the strings containing date?

Viewed 65
List<string> mylist = new List<string>()
{
    "element1", "02/18/2019", "element3", "03/17/2018"
};

In the above list I want to filter only element1 and element 3 and not the strings containing date. How Can I do that as I have no idea about that.

2 Answers
List<string> mylist = new List<string>()
{
    "element1", "02/18/2019", "element3", "03/17/2018"
}.Where(c => !DateTime.TryParse(c, out DateTime d)).ToList();

Edit: since the format is consistently MM/dd/yyyy, this should work regardless of the thread's locale:

List<string> mylist = new List<string>()
{
    "element1", "02/18/2019", "element3", "03/17/2018"
}.Where(c => 
    !DateTime.TryParseExact(c, "MM/dd/yyyy", CultureInfo.InvariantCulture, 
        DateTimeStyles.None, out DateTime d)
    ).ToList();

You can use the DateTime.TryParse in a loop. https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=netframework-4.8#System_DateTime_TryParse_System_String_System_DateTime__

List<string> mylist = new List<string>(new string[] { "element1", "02/18/2019", "element3","03/17/2018" });
var filteredLst = mylist.Where(_ => !DateTime.TryParseExact(_,  "MM/dd/yyyy" ,CultureInfo.InvariantCulture, out DateTime res)).ToList();

If you can be 100% certain of the date formats, you better use the TryParseExact flavor: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=netframework-4.8

Related