Home > Enterprise >  how to convert string values to date in C# from sharepoint API?
how to convert string values to date in C# from sharepoint API?

Time:12-21

I have an issue converting values from a column called OpeningDate in C# When i tried to convert where the value is null, the output "return error string parse"

I tried the following code in C#

// Get items from sharepoint list
  try
        {
            context.Load(items, its => its.Include(
            i => i.Id,
            i => i["SOQAssignmentCode"],
            i => i["OpeningDate"]
            ));
        }
        catch (Exception d)
        {
            ComponentMetaData.FireError(0, "", "Error on Load context SP Source."   d.Message, "", 0, out vbool);
        }
        try
        {
            context.ExecuteQuery();
        }
        catch (Exception d)
        {
            ComponentMetaData.FireError(0, "", "Error on ExecuteQuery SP Source."   d.Message, "", 0, out vbool);
        }

Conversion process which seems to be failed

try
        {
            //Récupérations des données
            string ac = string.Empty;
            string ast = string.Empty;
            string dateValue = null;
            string emptyString = "01/01/1900 00:00:00";
            string dateValue4 = null;




            foreach (ListItem listItem in items)
            {

                dateValue = listItem["OpeningDate"]?.ToString() ?? emptyString;
                dateValue4 = listItem["OpeningDate"]?.ToString() ?? null;

                var dateValue2 = DateTime.ParseExact(dateValue4,"yyyy/mm/dd", null);

                if (listItem["SOQAssignmentCode"] != null)
                {
                    foreach (ListItem item_not_to_take in listItems_not_to_take)
                    {
                        if (listItem["SOQAssignmentCode"].ToString() != item_not_to_take["SOQAssignmentCode"].ToString())

                            // MessageBox.Show(item_not_to_take["SOQAssignmentCode"].ToString());
                            ac = listItem["SOQAssignmentCode"].ToString();
                        
                        Output0Buffer.AddRow();
                        Output0Buffer.SOQAssignmentCode = ac;
                        Output0Buffer.SOQOpeningDate = dateValue2;
                        Output0Buffer.SPID = listItem.Id;

Would it be an easier method to get the string into date values ? How come the conversion seems to fail with empty/ null values ?

CodePudding user response:

The code is convertint the dates to strings at :

dateValue = listItem["OpeningDate"]?.ToString() ?? emptyString;
dateValue4 = listItem["OpeningDate"]?.ToString() ?? null;

The real solution is to not convert to strings in the first place but cast its value to the correct type, eg :

var openingDate = (DateTime?) listItem["OpeningDate"];

The same applies to other fields and types. Instead of calling ToString() on text fields, just cast the value to the correct type.

The variables themselves should be declared inside the loop, not outside. Otherwise it's very easy to end up using a value from a previous iteration before it receives its new value.

In the question's code for example, ac retains the previous iteration's value. The inner loop ends up assigning to the same output buffer multiple times, once for each item in listItems_not_to_take

Finally, a SharePoint list isn't a database table. Iterating over it and accessing values is expensive. Instead of trying to check every item in listItems_not_to_take it's better to extract the codes that aren't allowed in eg a Dictionary or HashSet and check with `Contains:

This snippet doesn't suffer from variable score creep :

var excluded=listItems_not_to_take.Select(item=>(string)item["SOQAssignmentCode"])
                                  .ToHashSet();

foreach (ListItem listItem in items)
{
    var openingDate=(DateTime?)listItem["OpeningDate"];
    var code = (string)listItem["SOQAssignmentCode"];

    if (code!=null && !excluded.Contains(code))
    {
        Output0Buffer.AddRow();
        Output0Buffer.SOQAssignmentCode = code;
        Output0Buffer.SOQOpeningDate = openingDate;
        Output0Buffer.SPID = listItem.Id;
    }
}
  • Related