简体   繁体   中英

How to perform transformations on strings in LINQ?

I have the below query that selects rows from a datatable called dtRows. The dtRows contains 2 columns FieldId and FieldValue and the FieldId contains values as below. When I select the FieldId's I need to strip the first two characters and convert the last character to a different string. For example, 1_3_1 should be 3_FirstName and 1_3_2 should be 3_LastName and 1_3_3 should be 3_MiddleName. Anyone has any suggestions?? Thanks a lot for any ideas!

FieldId Values:

1_1_1
1_1_2
1_1_3
1_2_1
1_2_2
1_2_3
1_3_1
1_3_2
1_3_3

var Names = from row in dtRows.AsQueryable()
                   where Convert.ToInt16(row.Field<string>("FieldId").Substring(2)) == prefix
                   select new
                   {
                       fieldId = 
           fieldValue = row.Field<string>("FieldValue")
                   };

I would write a function to calculate the different strings, and call it:

var Names = from row in dtRows.AsQueryable() 
               let id = row.Field<string>("FieldId")
               where Convert.ToInt16(id.Substring(2)) == prefix 
               select new 
               { 
                   fieldId = ConvertString(id),
                   fieldValue = row.Field<string>("FieldValue") 
               }; 

And

private string ConvertString(string original)
{
    // implementation left as an exercise
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM