215

My question is part of this problem:

I receive a collection of id's from a form. I need to get the keys, convert them to integers and select the matching records from the DB.

[HttpPost]
public ActionResult Report(FormCollection collection)
{
    var listofIDs = collection.AllKeys.ToList();  
    // List<string> to List<int>
    List<Dinner> dinners = new List<Dinner>();
    dinners= repository.GetDinners(listofIDs);
    return View(dinners);
}

15 Answers 15

503
listofIDs.Select(int.Parse).ToList()
Sign up to request clarification or add additional context in comments.

5 Comments

Exception raised - LINQ to Entities does not recognize the method 'Int32 IndexOf(Char)' method, and this method cannot be translated into a store expression. .net 4.0
@markthewizard1234 That will happen if your listofIDs is an IQueryable<string> that has not been executed. Execute it first with ToList() before you do the conversion: listofIDs.ToList().Select(int.Parse).ToList()
Im sure in 2013 this worked, but this no longer worked for me. Added a newer option below using linq statement.
This will throw an exception if any of the strings are not actually ints. See the safe versions down below. stackoverflow.com/a/48712010/2340825
@MichaelHornfeck The first ToList should be AsEnumerable, no need to allocate a second List
51

Here is a safe variant that filters out invalid ints:

List<int> ints = strings
    .Select(s => Int32.TryParse(s, out int n) ? n : (int?)null)
    .Where(n => n.HasValue)
    .Select(n => n.Value)
    .ToList();

It uses an out variable introduced with C#7.0.

This other variant returns a list of nullable ints where null entries are inserted for invalid ints (i.e. it preserves the original list count):

List<int?> nullableInts = strings
    .Select(s => Int32.TryParse(s, out int n) ? n : (int?)null)
    .ToList();

1 Comment

Great thanks! Version for C# 6.0 below stackoverflow.com/a/48712010/2340825
46

Using Linq ...

List<string> listofIDs = collection.AllKeys.ToList();  
List<int> myStringList = listofIDs.Select(s => int.Parse(s)).ToList();

Comments

24

What no TryParse? Safe LINQ version that filters out invalid ints (for C# 6.0 and below):

List<int>  ints = strings
    .Select(s => { int i; return int.TryParse(s, out i) ? i : (int?)null; })
    .Where(i => i.HasValue)
    .Select(i => i.Value)
    .ToList();

credit to Olivier Jacot-Descombes for the idea and the C# 7.0 version.

Comments

16

Using Linq:

var intList = stringList.Select(s => Convert.ToInt32(s)).ToList()

1 Comment

var intList = stringList.Select(Convert.ToInt32).ToList()
10

I know it's old post, but I thought this is a good addition: You can use List<T>.ConvertAll<TOutput>

List<int> integers = strings.ConvertAll(s => Int32.Parse(s));

1 Comment

This can be simplified to List<int> integers = strings.ConvertAll(int.Parse);
2

Convert string value into integer list

var myString = "010"; 
int myInt;
List<int> B = myString.ToCharArray().Where(x => int.TryParse(x.ToString(), out myInt)).Select(x => int.Parse(x.ToString())).ToList();

Comments

2

This may be overkill for this simple problem. But for Try-Do methods in connection with Linq, I tend to use anonymous classes for more expressive code. It is similar to the answers from Olivier Jacot-Descombes and BA TabNabber:

List<int> ints = strings
    .Select(idString => new { ParseSuccessful = int.TryParse(idString, out var id), Value = id })
    .Where(id => id.ParseSuccessful)
    .Select(id => id.Value)
    .ToList();

Comments

0

This is the simplest way, I think:

var listOfStrings = (new [] { "4", "5", "6" }).ToList();
var listOfInts = listOfStrings.Select<string, int>(q => Convert.ToInt32(q));

2 Comments

I see this kind of pattern in lambda expressions often: x => someMethod(x). You do know you should probably replace that with someMethod. With that your example becomes listOfStrings.Select<string, int>(Convert.ToInt32);. That's probably more readable, faster, shorter and did I already mention more elegant? The same goes for all others answering this question.
I'm getting an error when omitting the arrow syntax. This works: List<string> sss = new List<string>(); IEnumerable<int> test1 = sss.Select<string, int>(x => Convert.ToInt32(x)); but this does not: IEnumerable<int> test2 = sss.Select<string, int>(Convert.ToInt32); The error is ambiguous call between the string,int,int and string,int versions of Select.
0

Another way to accomplish this would be using a linq statement. The recomended answer did not work for me in .NetCore2.0. I was able to figure it out however and below would also work if you are using newer technology.

[HttpPost]
public ActionResult Report(FormCollection collection)
{
    var listofIDs = collection.ToList().Select(x => x.ToString());
    List<Dinner> dinners = new List<Dinner>();
    dinners = repository.GetDinners(listofIDs);
    return View(dinners);
}

Comments

0

You can use it via LINQ

     var selectedEditionIds = input.SelectedEditionIds.Split(",").ToArray()
                            .Where(i => !string.IsNullOrWhiteSpace(i) 
                             && int.TryParse(i,out int validNumber))
                            .Select(x=>int.Parse(x)).ToList();

1 Comment

Seems pretty wasteful to TryParse, which gives you the value, then simply throw that value out the window to then do a Parse. You're essentially double parsing.
0
intList = Array.ConvertAll(stringList, int.Parse).ToList();

Comments

0

This converts array of string to array of long. It returns number of successfully converted values.

public static int strv_to_longv(string[] src, int src_offset, long[] dst, int dst_offset)
{
    int i = src_offset;
    int j = dst_offset;
    int ni = src.Length;
    int nj = dst.Length;
    while ((i < ni) && (j < nj))
    {
        j += long.TryParse(src[i], out dst[j]) ? 1 : 0;
        i++;
    }
    return j;
}
var line = "lemon 4 grape 1 garlic 77";
string[] words = line.Split(' ');
long[] longs = new long[10];
int l = strv_to_longv(words, 1, longs, 0);
//longs will be equal {4, 1, 77}
//l will be equal 3

Comments

-1
  public List<int> ConvertStringListToIntList(List<string> list) 
  {
     List<int> resultList = new List<int>();
     for (int i = 0; i < list.Count; i++)
        resultList.Add(Convert.ToInt32(list[i]));

     return resultList;
  }

1 Comment

Consider adding some textual explanation about your answer, instead of providing code only.
-1
yourEnumList.Select(s => (int)s).ToList()

1 Comment

Hi Patryk. Welcome to StackOverflow. It would be better if you could write a little more description about the pretty concise solution you have posted. This is answer to a very old question on this website and would be reviewed by several users.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.