locked
linq list to array RRS feed

  • Question

  • User632751675 posted

    Hi,

    I want to put a linq list into an array so I can loop through it.

    So far I have this:   myLinqList[] newArray = linqList.ToArray(); //

    But, I don't know how to access to columns and rows.    When I debug, I can see this: newArray { mylinqlist[4]} , since I have four records or rows.

    I can access the columns, but only by name.  I want to do this by index because I have over 50 columns. 

    How would I set the list to a multi-dimensional array ?  Is that the solution?

    Tuesday, August 25, 2015 1:34 PM

Answers

  • User614698185 posted

    Hi maggiemays,

    According to your description, I create the sample code for you, code shown below:

    public string[,] GetCountryForUser(int userId)
    {
    
        var array  =(from xx in _er.UserRoles
                         join xy in _er.Countries on xx.CountryId equals xy.Id
                         join xz in _er.Manufacturers on xx.ManufacturerId equals xz.Id
                         where xx.UserId == userId
                         select new List<string>{ xy.Name, xz.Description }).ToArray(); 
        return CreateRectangularArray(array);  
    
    }
    
    
    static T[,] CreateRectangularArray<T>(IList<T>[] arrays)
    {
        // TODO: Validation and special-casing for arrays.Count == 0
        int minorLength = arrays[0].Count();
        T[,] ret = new T[arrays.Length, minorLength];
        for (int i = 0; i < arrays.Length; i++)
        {
            var array = arrays[i];
            if (array.Count != minorLength)
            {
                throw new ArgumentException
                    ("All arrays must be the same length");
            }
            for (int j = 0; j < minorLength; j++)
            {
                ret[i, j] = array[j];
            }
        }
        return ret;
    }
    

    For more information, please refer to the following links:

    http://docs.telerik.com/data-access/feature-reference/api/linq-guide/data-access-tasks-querying-model-convert-result-to-array

    http://jaanusvarus.com/using-linq-on-multidimensional-arrays/ 

    I hope this will help you.

    Best Regards,

    Candice Zhou

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 26, 2015 1:45 AM

All replies

  • User37182867 posted

    If you would post your code that you are using to generate your linq object I'm sure we can show you a better way than trying to use an Array to access the data in your Linq object.

    typically you can access the objects in your linq object or IQueryable or IEnumerable object like so

    Dim lo = GetDataFromDatabase()
    
    for each item in lo
       txtName.Text = item.PropertyName
    next
    

    By using a for each loop as above or by accessing it directly if you know what element you need to access like below 

    Dim lo = GetDataFromDatabase()
    
    myTxtName.text = lo(2).PropertyName

    Tuesday, August 25, 2015 1:40 PM
  • User632751675 posted

    hi,

    My list is based from a stored procedure  - resultset.toList().  I know I can access each column by name, but I didn't want to do it that way because in the long run, if my data changes, I dont want to have to maintain that.  So, being able to go by row and column helped.  I am working with a grid to get totals, that's why I want to do this.

    Tuesday, August 25, 2015 3:50 PM
  • User37182867 posted

    How are you returning your result set? Are you using Linq To SQL, Entity Framework, ADO.Net, Dapper?

    If you are using any of the above you don't have to convert a resultset to an array in order to step iterate through it. A list object is enumerable which means you can use a For Each statement on it. When you get your result back from your stored procedure it should be of an object type. As an example if you stored procedure select statement has 3 columns named ID, MyValue1, MyValue2 then the object returned would have properties associated with it named ID, MyValue1, MyValue2.

    In the case that MyValue2 was the number you wanted a running total of you could use a for each loop like this

    dim runningTotal as new integer
    for each result in resultset.toList
       runningTotal += result.MyValue2
    next
    

    However you could do the same thing using Linq

    dim runningTotal as integer
    runningTotal = (from result in resultset.tolist select result.MyValue2).Sum
    

    Tuesday, August 25, 2015 4:01 PM
  • User37182867 posted

    The only time that your data would change is if you changed your stored procedure. If you add new columns then the code above would be unaffected even if you changed the order of it. If you were to convert this to some datatable object and were to use values based on their column order then you would have to updated your code each time  you moved a column. 

    Tuesday, August 25, 2015 4:04 PM
  • User475983607 posted

    hi,

    My list is based from a stored procedure  - resultset.toList().  I know I can access each column by name, but I didn't want to do it that way because in the long run, if my data changes, I dont want to have to maintain that.  So, being able to go by row and column helped.  I am working with a grid to get totals, that's why I want to do this.

    There is not guarantee of property order within an object like you have in a datatable (ordinal).  If you want to do something fancy then you'll need to use reflection.

    Tuesday, August 25, 2015 4:08 PM
  • User632751675 posted

    Sorry - I'm using entity framework. thanks for your help.

    Tuesday, August 25, 2015 5:14 PM
  • User475983607 posted

    Sorry - I'm using entity framework. thanks for your help.

    I'm not sure what you're getting at... objects properties regardless of being populated from entity framework do not have any particular order. 

    Tuesday, August 25, 2015 7:29 PM
  • User614698185 posted

    Hi maggiemays,

    According to your description, I create the sample code for you, code shown below:

    public string[,] GetCountryForUser(int userId)
    {
    
        var array  =(from xx in _er.UserRoles
                         join xy in _er.Countries on xx.CountryId equals xy.Id
                         join xz in _er.Manufacturers on xx.ManufacturerId equals xz.Id
                         where xx.UserId == userId
                         select new List<string>{ xy.Name, xz.Description }).ToArray(); 
        return CreateRectangularArray(array);  
    
    }
    
    
    static T[,] CreateRectangularArray<T>(IList<T>[] arrays)
    {
        // TODO: Validation and special-casing for arrays.Count == 0
        int minorLength = arrays[0].Count();
        T[,] ret = new T[arrays.Length, minorLength];
        for (int i = 0; i < arrays.Length; i++)
        {
            var array = arrays[i];
            if (array.Count != minorLength)
            {
                throw new ArgumentException
                    ("All arrays must be the same length");
            }
            for (int j = 0; j < minorLength; j++)
            {
                ret[i, j] = array[j];
            }
        }
        return ret;
    }
    

    For more information, please refer to the following links:

    http://docs.telerik.com/data-access/feature-reference/api/linq-guide/data-access-tasks-querying-model-convert-result-to-array

    http://jaanusvarus.com/using-linq-on-multidimensional-arrays/ 

    I hope this will help you.

    Best Regards,

    Candice Zhou

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 26, 2015 1:45 AM