I would like to create a Dictionary from a list, so I would use this way:
Dictionary<long, List<MyType>> miDicIdMyType = myList.GroupBy(x => x.ForeignKey)
.ToDictionary(x => x.Key, x => x.ToList());
The problem is that sometimes the property can be null, so I can create the dictionary because a dictionary doesn't allow null values as key.
But in this particular case, I have to check if this property is null, and if it is null, throw an exception, because this is an error. In this particular method, I expect that all the items in the list have no null in this property.
So I would can do this:
Dictionary<long, List<MyType>> miDicIdMyType = myList.GroupBy(x => (long)x.ForeignKey)
.ToDictionary(x => x.Key, x => x.ToList());
It is a cast to long, but if it is null, I will get an error. So basically I wanted to do this:
Dictionary<long, MyType> myDic = new Dictionary<long, myType>();
foreach (Mytype iterator in miList)
{
if (iterator.ForeignKey == null)
{
throw new ArgumentNullException("Some items in the collection has null value and it is not expected.");
}
if (myDic.ContainsKey(iterator.ForeignKey) == false)
{
myDic.Add(iterator.ForeignKey, new List<MyType>());
}
myDic[iterator.ForeignKey].Add(iterator);
}
I would like to know if this is a good code or I could do it in a better way, with LINQ or a lambda expression or any other way. I mean, simplify my code.
x => x.ForeignKeyto a multiline lambda expessionFunc<T, long>and throw an exception in caseT.ForeignKeyis NULL. - Zein MakkiDictionary<long?, List<MyType>>. - Erik Philips