简体   繁体   中英

Translate from VB to C# for loop

I used a popular online code converter to go from VB to C# and the C# is not working on this for loop. Can any C# experts see the problem?

More specifically intellisense is telling me that CustomerRoles() cannot be used like a method. It works fine in VB.

VB:

 Dim Roles As New List(Of String)
 For x As Integer = 0 To EngineContext.Current.Resolve(Of IWorkContext)().CurrentCustomer.CustomerRoles().Count - 1
     Roles.Add(EngineContext.Current.Resolve(Of IWorkContext)().CurrentCustomer.CustomerRoles(x).Name)
     ddlRoles.Items.Add(EngineContext.Current.Resolve(Of IWorkContext)().CurrentCustomer.CustomerRoles(x).Name)
 Next

C# (this is not working) :

List<string> Roles = new List<string>();
for (int x = 0; x <= EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles().Count - 1; x++) {
  Roles.Add(EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles(x).Name);
  ddlRoles.Items.Add(EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles(x).Name);
}

Replace

CustomerRoles(x).Name

with

CustomerRoles[x].Name

You access the indexer of arrays (or lists) with squared brackets instead of paranthesis in C#.

If it's not a collection but a property or field you just have to remove the paranthesis:

CustomerRoles.Name

If that doesn't work(for whatever reason) you can try Enumerable.ElementAt :

CustomerRoles.ElementAt(x).Name

That works with any kind of IEnumerable<T> even if it doesn't implement IList<T> (needed for the indexer).

Try this:

C#(this is not working)
List<string> Roles = new List<string>();
for (int x = 0; x <= EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles.Count - 1; x++) {
    Roles.Add(EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles[x].Name);
    ddlRoles.Items.Add(EngineContext.Current.Resolve<IWorkContext>().CurrentCustomer.CustomerRoles[x].Name);
}

Ok i've tried in VB CustomerRoles(x) is equivalent to CustomerRoles.ElementAtOrDefault(x); in c#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM