开发者

Type Casting Part of a string to int in where clause LinQ C#

I have a collection of string names, few names starts with X100,x200,x121 which has numeric values. I'm using LinQ to loop thro and also using a where clause to filter those names that has integer values like x"100." Which is the best way to do accompolish this?. is it possible to use Func or Action on the items for checking each string variable.My

where clause in expression looks something like this

   var columns = from c in factory.GetColumnNames("eventNames")
                              where c.Substring(1) // I dont know what to do next
                              select c;

.if the next string is "c.substring(1)" integer obviously the names are wrong.So is there any best way to do this check and return a string collec开发者_StackOverflowtion


To find all strings that contain an integer, you could use

var columns = from c in factory.GetColumnNames("eventNames") 
              where Regex.IsMatch(c, @"\d+")
              select c; 


Try this to select all the rows that are like "x100" etc.

int tmp;
var columns = from c in factory.GetColumnNames("eventNames") 
  where int.TryParse(c.Substring(1), out tmp)
  select c; 

Try this to select all rows, converting "x100" to "100" and leaving the rest as is.

int tmp;
var columns = from c in factory.GetColumnNames("eventNames") 
  select (int.TryParse(c.Substring(1), out tmp) ? tmp.ToString() : c); 

If neither of these are what you want please clarify.


Try something like:

var columns = from c in factory.GetColumnNames("eventNames")
                          where CharactersAfterFirstAreInteger(c)
                          select c;

private bool CharactersAfterFirstAreInteger(string stringToCheck)
{
  var subString = stringToCheck.SubString(1);
  int result = 0;

  return int.TryParse(subString, out result);
}

This gives you the flexibility to alter the signature of CharactersAfterFirstAreInteger, if you needed to, so you could perform additional checks, for example, so that only values where the numeric part were greater than 200 were returned..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜