1

any help on this scenario please.. new to c#.

Summary:

  1. Need to read the contents of csv into array.
  2. Skip first line of array, then sort on column 1 (company)
  3. Then use sorted array (without header if easier) further along in code.

Example csv:

 Company,Item,Vendor
 Comp1,Bulb,BnQ
 Comp2,Plug,Tesco
 Comp1,Kettle,Wickes

This is my attempt but I get the following error when attempting to access sorted[j] and I cant work out a way around this.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable

Code:

var csvRows = System.IO.File.ReadAllLines(filename).Skip(1);
var sorted = csvRows.Select(line => new
                {
                    SortKey = Int32.Parse(line.Split(',')[0]),
                    Line = line
                })
                .OrderBy(x => x.SortKey)
                .Select(x => x.Line);

int maxCount = sorted.Count();

for (int j = 0; j < maxCount; j++)
{
 string line1 = sorted[j].ToString();
 var values = line1.Split(',');
...
6
  • 1
    Pretty sure adding .ToList() will work: .Select(x => x.Line).ToList();, otherwise you can foreach instead of for: foreach (var line in sorted) { var line1 = line.ToString(); ... Commented Mar 3, 2017 at 15:55
  • @Quantic thanks, I will give this a go and see if it works for me Commented Mar 3, 2017 at 16:00
  • 2
    You should really learn to Google these exception messages. Typing Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable directly into Google tells you how to fix it. Commented Mar 3, 2017 at 16:25
  • @DarrenYoung appreciate the advice, albeit condescending. It was the first thing I did, but still failed to find a solution - hence the post. Commented Mar 3, 2017 at 16:34
  • When I do as @DarrenYoung says I get Cannot apply indexing with __ to an expression of type 'System.Collections.Generic.ICollection<int> in mvc controller and cannot apply indexing with __ to an expression. Commented Mar 3, 2017 at 17:22

1 Answer 1

2

You need to add .ToList() or .ToArray()to the end of the LINQ query, otherwise your sorted variable is IEnumerable and not list or array, so you cant access it with an index.

Sign up to request clarification or add additional context in comments.

Comments

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.