选择Linq中Datatable数据行中的大小写

时间:2013-12-04 05:42:22

标签: c# linq

我有一个DataTable,它有3个列,如IsMonday,Istuesday和IsWednesday,两个都是字符串字段,有Y和NI这样的数据想要获取每一行并以字符串形式返回结果。我想得到的是,< / p>

    if a row is Y,N,Y then the output will be 1 3,two is blank since it is N
    if a row is N,N,Y then the output will be   3,one and two is blank since it is N

像这样,使用Linq case语句或任何其他方式的任何想法

2 个答案:

答案 0 :(得分:4)

考虑到您从数据库返回的行集合看起来与此List类似。

var entity = new List<Entity>()
 {
 new Entity(){ IsMonday = "Y", IsTuesday = "N", IsWednesday = "Y"},
 new Entity() { IsMonday = "N", IsTuesday = "N", IsWednesday = "Y"},
 new Entity() { IsMonday = "Y", IsTuesday = "Y", IsWednesday = "N"}
 };

要获得预期的结果,您可以使用类似这样的代码

 foreach (var e in entity)
 {
   var a = e.IsMonday.Equals("y", StringComparison.OrdinalIgnoreCase) ? "1" : " ";
   var b = e.IsTuesday.Equals("y", StringComparison.OrdinalIgnoreCase) ? "2" : " ";
   var c = e.IsWednesday.Equals("y", StringComparison.OrdinalIgnoreCase) ? "3" : " ";
   var s = String.Format("{0} {1} {2}", a, b, c);
 }

这里的变量&#39;包含结果字符串。

答案 1 :(得分:2)

这会将所有行转换为List<string>

var columnNames = new[]{"IsMonday","Istuesday","IsWednesday"};
var rows = dt.AsEnumerable()
             .Select(row=>string.Join("", 
                          dt.Columns.Cast<DataColumn>()
                            .Where(col=>columnNames.Contains(col.ColumnName))
                            .Select(col=>row.Field<string>(col) == "N" ? " " :
                                         (col.Ordinal+1).ToString()))).ToList();

请注意,您说"N"之类的内容将替换为空白,但看起来您的意思是空间,所以我使用了空格代替,你可以把它换成你想要的任何东西。

如果您只想将特定行转换为字符串,则它非常相似:

//the input is row
var rowString = string.Join("", 
                  dt.Columns.Cast<DataColumn>()
                            .Where(col=>columnNames.Contains(col.ColumnName))
                            .Select(col=>row.Field<string>(col) == "N" ? " " :
                                         (col.Ordinal+1).ToString())).ToList();