Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

c# - Inserting the first value of a key-value pair, when the value is a list

I have a dictionary as below, where the key is a string and the value is a list of doubles:

Dictionary<string, List<double>> dataStore = new Dictionary<string, List<double>>();
List<string> channel_names = new List<string>(); // contains the keys

Now when I want to add data to this dictionary, I do:

if (dataStore.ContainsKey(channel_names[j]))
{
    dataStore[channel_names[j]].Add(measurement);
}
                            
else
{
    dataStore.Add(channel_names[j], new List<double>((int)measurement));
}

The first statement (adding to an existing key) works fine, but something is wrong with the second statement, i.e. when I am trying to initialise the keys with the first double in the list. The first measurement is being missed out. Can anyone please advise as to why?

Thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are using the constructor List(int), where int specifies the initial capacity of the list; it does not add that number to the list.

You could instead use collection-initialiser syntax:

new List<double> { measurement }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...