C# facing problem to add data into List<T> from LINQ select function

T.Zacks 3,996 Reputation points
2022-02-04T13:39:05.287+00:00

please have a look this code

            List<string> lst = new List<string>();
            IEnumerable<int> squares = Enumerable.Range(0, 3).Select(x => new
            {
                lst.Add(x.ToString())
            });

within select function can't we add anything to List<T> ?

where i made the mistake in code? please tell me how to achieve what i am trying to do. thanks

Developer technologies | C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2022-02-04T13:47:02.303+00:00

    Try this instead:

    foreach (var x in Enumerable.Range(0, 3)) {
        lst.Add(x.ToString());
    }
    

    The .Select() method is for projecting/mapping from one set of values to another, so the function that you pass to it need to return a value. In your case you're returning an anonymous object (i.e. new { }) but you're calling lst.Add() inside the body of the object which is a syntax error.

    You could also do it in one line like this:

    List<string> lst = Enumerable.Range(0, 3).Select(x => x.ToString()).ToList();
    

  2. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-02-04T19:53:42.217+00:00

    Seems this would provide what you are after

    List<string> stringList = new();
    List<int> intList = new();
    
    void AddToList(int value)
    {
        stringList.Add(value.ToString());
        intList.Add(value);
    }
    
    Enumerable.Range(0, 3).ToList().ForEach(AddToList);
    

    Or

    var intArray = Enumerable.Range(0, 3).Select(x => x).ToArray();
    string[] strArray = Array.ConvertAll(intArray, value => value.ToString());
    

    Neither are one liners but that should not matter

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.