简体   繁体   中英

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 collection

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.

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 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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM