質問

i am accesing the google books api to access their record. the problem is that they are having publish date as string. Apart from string they are having records as 12-june, june etc which are not valid datetime. now i want to select records between two dates in the example below between valid dates.how can i do that?

        List<datetest> datetest = new List<datetest>();
        datetest.Add(new datetest { stringdate = "13-june" });
        datetest.Add(new datetest { stringdate = "June" });
        datetest.Add(new datetest { stringdate = "2010-09-11" });
        datetest.Add(new datetest { stringdate = "2010-09-10" });
        datetest.Add(new datetest { stringdate = "2014-09-09" });

i have tried date.parse and parseexact which is not working with the format. i am not sure about tryparse. how can i make it work in the linq query. any other thing?

役に立ちましたか?

解決

based on this answer How to I use TryParse in a linq query of xml data?

Func<string, DateTime?> tryToGetDate = value =>
{
    DateTime dateValue;
    return DateTime.TryParse(value, out dateValue)
        ? (DateTime?) dateValue
        : null;
};

var dates = (
    from c in datetest
    where tryToGetDate(c.stringdate) != null
    select c
).ToList();

他のヒント

This will give you all of the valid dates:

var dates = datetest.Select(x =>
    {
        DateTime date;
        if (DateTime.TryParse(x.stringdate, out date))
            return date;

        return (DateTime?)null;
    }).Where(x => x.HasValue).ToList();

If you want to include the invalid dates as nulls, you can remove the .Where condition.

Also note that 13-june will be assumed to have the current year.

You are going to have to write individual conditions for each format. Basically, try to DateTime.Parse it, and if it fails, attempt to evaluate it for each possible format that you may have to parse.

If you just want to replace invalid dates with null, do something like this for each value:

DateTime Out = null;
DateTime.TryParse("YourString",out Out);

For example, if you have an array of strings (called Array):

DateTime?[] Result = Array.Select(x => 
{
    DateTime Out = null;
    DateTime.TryParse("YourString",out Out);
    return Out;
}).ToArray();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top