拆分字符串以获取ID的数量? [英] split the string to get count of ids ?

查看:132
本文介绍了拆分字符串以获取ID的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个字符串变量,其中包含

 120,130,134,138,151,3810 





i只想得到不同的id数。



请建议

解决方案

试试这个:



  string  s =   120,130,134,138,151,3810 ; 

var qry = s.Split(' ,'
。选择(a => Convert.ToInt32(a.Trim()))
.GroupBy(a => a)
.Select(grp => new
{
value = grp.Key,
count = grp.Count()
});





结果:

 值算上 
120 1
130 1
134 1
138 1
151 1
3810 1









  var  qry = s.Split(' ,'
。选择(a => Convert.ToInt32(a.Trim()))
.Distinct()
.Count();
// returs:6







根据OP评论:



< pre lang =cs> List< string> s = new 列表< string>()
{
120,130,134,138,151,3810
null
120,130,134,202,1151,3810
};

var qry = s.SelectMany(a = > (a? ? string .Empty).Split( new char [] {' ,'' '},StringSplitOptions.RemoveEmptyEntries))
.Distinct()
.Count();
// 返回:8


将字符串转换为数组或List< string>使用string.Split(变量,',')

确保修剪空格。

然后你可以使用Linq选择不同的。


Hi ,

I have one string variable which contains

120, 130, 134, 138, 151, 3810



i just want to get distinct id count .

Please suggest

解决方案

Try this:

string s = "120, 130, 134, 138, 151, 3810";
 
var qry = s.Split(',')
        .Select(a=>Convert.ToInt32(a.Trim()))
		.GroupBy(a=>a)
		.Select(grp=>new
			{
				value = grp.Key,
				count = grp.Count()
			});



Result:

value count
120   1
130   1
134   1
138   1
151   1
3810  1



[EDIT]

var qry = s.Split(',')
        .Select(a=>Convert.ToInt32(a.Trim()))
        .Distinct()
        .Count();
//returs: 6



[EDIT2]
According to OP comments:

List<string> s = new List<string>()
        {
            "120, 130, 134, 138, 151, 3810",
            null,
            "120, 130, 134, 202, 1151, 3810"
        };

var qry = s.SelectMany(a=>(a ?? string.Empty).Split(new char[]{',', ' '}, StringSplitOptions.RemoveEmptyEntries))
        .Distinct()
        .Count();
//returns: 8


Convert the string into an array or List<string> using string.Split(variable,',')
Make sure you trim the spaces.
You can then use Linq to select distinct.


这篇关于拆分字符串以获取ID的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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