如何获取用数据表C#中的单引号括起来的逗号分隔列表 [英] How to get comma seprated list enclosed with single quotes from a datatable C#

查看:67
本文介绍了如何获取用数据表C#中的单引号括起来的逗号分隔列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友们,



我需要从数据表列中获取逗号分类列表。这部分我能够完成。但我的要求是在每个项目之间加上单引号。

例如'ÁBC','DEF','GHI'

我需要得到这样的输出。任何人都可以修改我的代码以获得所需的输出。目前我正在回收字符串数组,但我很高兴,如果我能得到一个字符串



Hi Friends,

I need to get a comma sperated list from a datatable column. This part i am able to complete. But my requirement is to enclose single quotes between each item.
For example 'ÁBC','DEF','GHI'
I need to get output like this. Can any one please modify my code to get the desired output. Currently i am returing array of string but i am happy if i can get as a string

public static string[] GetCommaSperatedList(DataTable dt)
{
  string[] allitems = dt.AsEnumerable()
                         .SelectMany(r => r.Field<string>("IN_KEY_TMS").Split(','))
                         .ToArray();
  return allitems;
}





提前致谢



Thanks in advance

推荐答案

返回单引号包围的内容使用 ConvertAll 例如
To return the contents surrounded by single quotes use ConvertAll e.g.
Array.ConvertAll(allitems, z => "'" + z + "'");



将它们全部合并为一个字符串(一旦被引号括起来)然后使用加入

return String.Join(",", Array.ConvertAll(allitems, z => "'" + z + "'"));







结合这两行...在我提供的代码中使用allitems来剪切和粘贴派生 allitems 的位,即




Just combine the two lines...cut&paste the bit that derives allitems over the use of "allitems" in the code I supplied i.e.

public static string GetCommaSperatedList(DataTable dt)
{
  return String.Join(",",Array.ConvertAll(dt.AsEnumerable()
                         .SelectMany(r => r.Field<string>("IN_KEY_TMS").Split(',')).ToArray(), z => "'" + z + "'"));
}



注意我已将函数的返回类型从string []更改为string。



另外注意!

如果您计划在SQL查询中使用此字符串,并且如果数据表已受到用户输入的影响/创建,那么您可能会将代码暴露给风险SQL注入。如果是这种情况,那么还要考虑Richard Deeming的解决方案使用用户输入数组从数据库中获取特定值。它适用于单个项目,但不适用于itemid列表 [ ^ ]


试试这个:



Try this:

public static string[] GetCommaSperatedList(DataTable dt)
{
  return String.Join(",", dt.AsEnumerable()
                         .SelectMany(r => r.Field<string>("IN_KEY_TMS").Split(',')).ToArray());
}


这篇关于如何获取用数据表C#中的单引号括起来的逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆