Reputation: 307
From a datatable I am fetching the value and putting in a Dictionary<string,string>
:
Dictionary<string, string> mydic= new Dictionary<string, string>();
my datatable for ex is
Value RowOrder
page1 01
page2 00
page3 00
I am using LINQ to fetch the RowOrder
according to value given and putting into mydic
:
string id = (from DataRow dr in table3.Rows where (string)dr["Value"] == formula
select (string)dr["RowOrder"]).FirstOrDefault();
mydic.Add(id,Value);
If I run this, error is showing:
"An item with the same key has already been added."
How to overcome this. I want page1
, page2
, page3
should be added with values 01
, 00
, 00
respectively
Upvotes: 5
Views: 16827
Reputation: 236228
Check if key exists before adding
if (mydic.ContainsKey(id))
mydic[id] = Value; // or throw exception
else
mydic.Add(id, Value);
BTW if you want to convert your DataTable
to Dictionary<string, string>
with RowOrder as key, and first (or last) Value as value, you can use LINQ:
var mydic = table3.AsEnumerable()
.GroupBy(r => r.Field<string>("RowOrder"))
.Select(g => g.First()) // or last to use last value for key
.ToDictionary(r => r.Field<string>("RowOrder"),
r.Field<string>("Value"));
Upvotes: 3
Reputation: 32561
You may use a Lookup<string,string>
:
List<Tuple<string, string>> tuples = new List<Tuple<string, string>>();
tuples.Add(new Tuple<string, string>("01", "page1"));
tuples.Add(new Tuple<string, string>("00", "page2"));
tuples.Add(new Tuple<string, string>("00", "page3"));
var lookup = tuples.ToLookup(t => t.Item1,t=> t.Item2 );
And you may use it like:
var result = lookup["00"];
foreach (var item in result)
{
Console.WriteLine(item);
}
Which outputs:
page2 page3
Upvotes: 0
Reputation: 2375
Use
mydic[id] = Value;
instead of mydic.Add(); The Add method should be used if you want to ensure only one item with a given key is inserted. Note that this overwrite the previously written value.
If you want to have more items with the same key you should use a
Dictionary<string, IList<string>>
or some other datastructure I don't know of but I would be very glad to hear about since I used that kind of dictionary more than once
Upvotes: 1
Reputation: 14618
You need to check whether the dictionary already has the key before adding to it:
if(!mydic.ContainsKey(id))
{
mydic.Add(id, Value);
}
A dictionary cannot contain two items with the same key, if you are expecting duplicate id values you need to consider using a different data structure.
Perhaps a List<Tuple<string, string>>
?
Upvotes: 9
Reputation: 460138
You can use GroupBy
, here a single line approach using Linq-To-DataSet
:
Dictionary<string, string> mydic = table3.AsEnumerable()
.GroupBy(row => row.Field<string>("Value"))
.ToDictionary(grp => grp.Key, grp => grp.First().Field<string>("RowOrder"));
Upvotes: 1