如何在LINQ中对字符串执行转换?

时间:2012-04-12 19:00:50

标签: c#

我有以下查询从名为dtRows的数据表中选择行。 dtRows包含2列FieldId和FieldValue,FieldId包含如下值。当我选择FieldId时,我需要去掉前两个字符并将最后一个字符转换为另一个字符串。例如,1_3_1应为3_FirstName,1_3_2应为3_LastName,1_3_3应为3_MiddleName。任何人都有任何建议?非常感谢任何想法!

FieldId值:

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")
                   };

1 个答案:

答案 0 :(得分:0)

我会写一个函数来计算不同的字符串,并调用它:

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") 
               }; 

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