Question

I'm fairly new to C# and receiving an error when I try to access an element of an array inside another array. The object itself it a custom class, which may be the reason why I'm having an issue.

Here's a generic example:

My data is structured as follows:

public class Item
{
    public string name = "";
    public int var1 = 0;
    public int var2 = 0;
}

Item item1 = new Item1();

public class Item1 : Item
{
    public Item1()
    {
        name = "Item 1";
        var1 = 10;
        var2 = 100;
    }
}

I then created lists of these items (using lists because the dimensions are variable). I convert them to arrays because I plan on using the LINQ cartesian function.

List<Item> itemlist1 = new List<Item>();
List<Item> itemlist2 = new List<Item>();
List<Item> itemlist3 = new List<Item>();

itemlist1.Add(item1);
itemlist1.Add(item2);
itemlist2.Add(item3);
itemlist2.Add(item4);
itemlist3.Add(item5);
itemlist4.Add(item6);

Item[] itemarr1 = itemlist1.ToArray();
Item[] itemarr2 = itemlist2.ToArray();
Item[] itemarr3 = itemlist3.ToArray();

Here I use the LINQ cartesian function like so:

var itemcombo = from itemset1 in itemarr1
                from itemset2 in itemarr2
                from itemset3 in itemarr3
                select new[] { itemset1, itemset2, itemset3 }.ToList();

From here, I can't access any of the array elements. Trying to access itemcombo[x] gives the error:

"Cannot apply indexing with [] to an expression of type System.Collections.Generic.IEnumerable<System.Collections.Generic.List<ItemExample.MainWindow.Item>>'"

I've tried converting it to a list, to an array. I can't seem to figure out how to access itemcombo[0][0].name for example.

Thanks in advance for any tips and/or solutions!

Was it helpful?

Solution

You need parentheses around the query

(from itemset1 in itemarr1
 from itemset2 in itemarr2
 from itemset3 in itemarr3
 select new[] { itemset1, itemset2, itemset3 }).ToList();

OTHER TIPS

I don't think the [] works with IEnumerable types. Instead of :

    itemcombo[x]

try using:

    itemcombo.ElementAt(x)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top