Iterate Over A Collection in C#
I have the following classes created:
[Serializable]
public class AppContext : IXmlSerializable {
public string reportType = string.Empty;
public string entityId = string.Empty;
// OPTIONS
public IDictionary<string, OPTIONS> dict_Options = new Dictionary<string, OPTIONS>();
// Advan开发者_开发技巧ced Options
public List<string> listAdvancedOptions = new List<string>();
public class OPTIONS {
public string subjectId = string.Empty;
public string varNumber = string.Empty;
}
}
How do I iterate over the OPTIONS to get all the varNumbers?
Method 1
foreach (KeyValuePair<string, AppContext.OPTIONS> kvp in appContext.dict_Options)
{
Console.WriteLine(kvp.Value.varNumber);
}
Method 2
foreach (AppContext.OPTIONS item in appContext.dict_Options.Values)
{
Console.WriteLine(item.varNumber);
}
Method 3
foreach (string item in appContext.dict_Options.Select(x => x.Value.varNumber))
{
Console.WriteLine(item);
}
A Dictionary<TKey, TVal>
implements IEnumerable<KeyValuePair<TKey, TVal>>
, so try this:
var varNumbers = dict_Options.Select(kvp=>kvp.Value.varNumber);
You can also access an IEnumerable of the values of the dictionary directly:
var varNumbers = dictOptions.Values.Select(v=>v.varNumber);
OPTIONS
is a class that doesn't implement any collection interface (say IEnumerable
). You can't iterate over it.
You can iterate over your dictionary - dict_Options
:
foreach(var item in dict_Options)
{
// use item - say item.varNumber
}
Note:
Having public fields in your class is bad design - it violates encapsulation and information hiding and will make it difficult to evolve the class. You should be using private fields and public properties to expose them.
If you just want to loop over all of the varNumbers I would probably do the following:
var dict_Options = new Dictionary<string, OPTIONS>();
foreach (var varNumber in dict_Options.Select(kvp => kvp.Value.varNumber))
{
// Your code.
}
精彩评论