1

Need your help: I have Datable that has datarows like :

test1
test1:1
test1:1:1
test1:2

I need to select only rows that contain ":" only once. Result should be like : test1:1 test1:2

Any ideas how to make it ?? I stuck after :

var result = dTable.AsEnumerable().Where(dr => dr.Field<string>("Name").Contains(":"));

,where "Name" is a column Name.

Thank you in advance

Ros
  • 37
  • 6

3 Answers3

1
var result = dTable.AsEnumerable()
  .Where(dr => dr.Field<string>("Name").Count(z=>z==':')==1);

or

var result = dTable.AsEnumerable()
  .Where(dr => dr.Field<string>("Name").Where(z=>z==':').Count()==1);

or

var result = dTable.AsEnumerable()
  .Where(dr => dr.Field<string>("Name").IndexOf(':') == dr.Field<string>("Name").LastIndexOf(':') && dr.Field<string>("Name").Contains(":"));
Robert McKee
  • 21,305
  • 1
  • 43
  • 57
1

You can convert the content of the Field to a Char array and then count the number of times you get the ':'

var result = dt.AsEnumerable()
               .Where(dr => dr.Field<string>("Name")
               .ToCharArray()
               .Count(c => c == ':') == 1);
Steve
  • 213,761
  • 22
  • 232
  • 286
0

Try this instead:

var result = dTable.AsEnumerable().Where(dr => dr.Field<string>("Name").Count(f => f == ':') == 1);

With LINQ, this is very easy using x.Count().

If you want to do it without LINQ, try this:

var result = dTable.AsEnumerable().Where(dr => dr.Field<string>("Name").Split(':').Length - 1 == 1);

See the top answer at this other Stack Overflow question, which has something similar. I don't usually use LINQ, so forgive me if my code doesn't work. Hope this helps!

Daniel Reynolds
  • 142
  • 1
  • 13