2

Help me how to compare part of the string date in the string with the exact datetime in C#.NET using Linq or any easy way??

Example:

//  10/23/2013 03:43:56 PM
string fileImageName = "Picture_MIGA1_2013_10_23_15_43_56.png";
4

1 回答 1

4

使用DateTime.TryParseExact(除其他外):

DateTime toCompare = new DateTime(2013, 10, 23, 15, 43, 56);
string fileImageName = "Picture_MIGA1_2013_10_23_15_43_56.png";
var tokens = Path.GetFileNameWithoutExtension(fileImageName).Split('_');
// take last 6 because there are the datetime informations in the filename
var dateTokens = tokens.Skip(Math.Max(0, tokens.Length - 6)).Take(6).ToArray(); 
if (dateTokens.Length == 6)
{
    DateTime dt;
    DateTime.TryParseExact(
        string.Join("_", dateTokens),
        "yyyy_MM_dd_HH_mm_ss",
        CultureInfo.InvariantCulture,
        DateTimeStyles.None,
        out dt);
    bool isSame = toCompare == dt;  // true
}

编辑

我如何用 LinQ 查询编写

你没有提到你有什么类型的收藏。List<string>因此,为了简单起见,我展示了一个带有 a 的示例:

var fileNames = new List<string>() { "Picture_MIGA1_2013_10_23_15_43_56.png" };
List<string> allMatching = fileNames
.Where(fn =>
{
    var tokens = Path.GetFileNameWithoutExtension(fn).Split('_');
    var dateTokens = tokens.Skip(Math.Max(0, tokens.Length - 6)).Take(6).ToArray();
    if (dateTokens.Length == 6)
    {
        DateTime dt;
        DateTime.TryParseExact(
            string.Join("_", dateTokens),
            "yyyy_MM_dd_HH_mm_ss",
            CultureInfo.InvariantCulture,
            DateTimeStyles.None,
            out dt);
        return toCompare == dt;
    }
    return false;
}).ToList();
于 2013-10-23T14:06:40.100 回答