I have a List and MyClass is:
public class MyClass
{
public bool Selected { get; set; }
public Guid NoticeID { get; set; }
public Guid TypeID { get; set; }
}
My question is, how do i convert this list into a Dictionary<Guid, List<Guid>>, where the dictionary key is the GUID from the TypeID property, and the value is a list of all the NoticeID values corresponding to that TypeID. I have tried like so:
list.GroupBy(p => p.TypeID).ToDictionary(p => p.Key, p => p.ToList())
but this returns a Dictionary <Guid, List<MyClass>>, and I want a Dictionary<Guid, List<Guid>>.
Well, when you group you can specify the value you want for each element of the group:
var dictionary = list.GroupBy(p => p.TypeID, p => p.NoticeID)
.ToDictionary(p => p.Key, p => p.ToList());
However, I would strongly consider using a lookup instead of a dictionary:
var lookup = list.ToLookup(p => p.TypeID, p => p.NoticeID);
Lookups are much cleaner in general:
They're immutable, whereas your approach ends up with lists which can be modified
They express in the type system exactly what you're trying to express (one key to multiple values)
They make looking keys up easier by returning an empty sequence of values for missing keys, rather than throwing an exception
Related
I have a dictionary Dictionary<string, List<string>> MatrixColumns whose content looks like this:
Now, I want to iterate over MatrixColumns Dictionary in such a way that I first get "condition#1" of [0] of key "OPERATOR_ID" and then "delta#1" of [0] of key "DELTA_ID"
and then again "condition#1" of 1 of key "OPERATOR_ID" and then "delta#1" of 1 of key "DELTA_ID" and so on.
Thing to keep in mind is the count of elements inside MatrixColumns can vary and it's not always 2. pls. guide me, How Can I achieve this?
Create a class:
public class MatrixColumnDto
{
public string ColumnName { get; set; }
public List<string> ColumnValues { get; set; }
}
Use LINQ as:
var MatrixColumnsResult = Enumerable.Range(0, MatrixColumns.Max(list
=> list.ColumnValues.Count))
.Select(i => MatrixColumns.Select(list => list.ColumnValues.ElementAtOrDefault(i)).ToList())
.ToList();
I have a dictionary which holds information from a parsed test run. The key is the name of the method and the value is a list of TestRunProperties. My dictionary contains all methods from a test run and I would like to remove the methods which failed during a test run. Is this possible to do with Linq?
TestRunProperties class:
public class TestRunProperties
{
public string computerName { get; set; }
public TimeSpan duration { get; set; }
public string startTime { get; set; }
public string endTime { get; set; }
public string testName { get; set; }
public string outcome { get; set; }
}
Dictionary:
//Key is the name of the method, value is the properties associated with each run
private static Dictionary<string, List<TestRunProperties>> runResults = new Dictionary<string, List<TestRunProperties>>();
I've tried this but I think I'm getting confused with the Where part:
runResults.Remove(runResults.Where(methodName => methodName.Value.Where(method => method.outcome.ToLower().Equals("failed"))));
I'm quite new to Linq and Lambda and I'm still trying to understand how to access data like this.
Just use a loop to remove the items you don't want. You can write an extension method to make it easier to call:
public static class DictionaryExt
{
public static void RemoveAll<K, V>(this IDictionary<K, V> dict, Func<K, V, bool> predicate)
{
foreach (var key in dict.Keys.ToArray().Where(key => predicate(key, dict[key])))
dict.Remove(key);
}
}
This usually will be more efficient than creating an entirely new dictionary, especially if the number of items being removed is relatively low compared to the size of the dictionary.
Your calling code would look like this:
runResults.RemoveAll((key, methodName) => methodName.Value.Where(method => method.outcome.ToLower().Equals("failed")));
(I chose the name RemoveAll() to match List.RemoveAll().)
You could create a new dictionary by filtering out the invalid ones:
var filtered = runResults.ToDictionary(p => p.Key, p => p.Value.Where(m => m.outcome.ToLower() != "failed").ToList());
Ok, grrrrrr was faster :-)
To be honest you're probably better off selecting a new dictionary from the existing one:
runResults.Select().ToDictionary(x => x.Key, x => x.Value.Where(x => x.Value.outcome != "failed"));
*editted to reflect list in the dictionary.
Actually, you can get rid of the ones with no successful results by doing this too:
runResults.Select(x => new { x.Key, x.Value.Where(x => x.Value.outcome != "failed")} ).Where(x => x.Value.Any()).ToDictionary(x => x.Key, x => x.Value);
I'm trying to convert a list of objects to a dictionary using the following code:
var MyDictionary = MyList.Distinct().ToDictionary(i => i.ObjectId, i => i);
I know that a dictionary should not contain duplicate elements, hence the .Distinct(). Yet I still get the following Exception whenever there's a duplicate element:
An item with the same key has already been added.
MyList is a list of MyObject that looks like this:
public class MyObject{
public string ObjectId { get; set; }
public string FName { get; set; }
public string LName { get; set; }
}
Is there a better way to create a dictionary from a list of objects ? or am I doing something wrong?
If you want to compare on the ObjectId, you'll need to pass in a custom comparer to .Distinct(). You can do so like this:
class MyObjectComparer : IEqualityComparer<MyObject>
{
public bool Equals(MyObject x, MyObject y)
{
return x.ObjectId == y.ObjectId;
}
public int GetHashCode(MyObject obj)
{
return obj.ObjectId.GetHashCode();
}
}
var MyDictionary = MyList
.Distinct(new MyObjectComparer())
.ToDictionary(i => i.ObjectId, i => i);
You could use Group by and then select first from the List as below:
var MyDictionary = MyList.GroupBy(i => i.ObjectId, i => i).ToDictionary(i => i.Key, i => i.First());
Distinct works using the objects built in Equals and GetHashCode methods by default but your dictionary works only over the id. You need to pass in a IEqualityComparer in to distinct that does the comparison on Id to test if items are equal or make MyObject implment Equals and GetHashCode and have that compare on the Id.
Suppose i have two (could be more) lists of same object having same fields/properties.
Each list represent the same object
Proerpties:
HoursWorked
HoursRate
I want to take iterate and take sum of each field from all lists (could be 2, 3, or so on) and store it in an dictionary with key value pair. e.g HoursWorked:2 and HourseRate:6
Currently, i am able to do it for only one field only (hard coded). I want to make it generic so i can fill dictionary with Key/Value for all fields.
I have defined my dictionary as follow
public Dictionary<string, double> TotalCount { get; set; }
Linq Query:
Dictionary<string, double> totalCount = records
.GroupBy(x => records)
.ToDictionary(x => Convert.ToString("HoursWorked"), x => x.Where(y => y.HoursWorked != null).Sum(y => y.HoursWorked).Value);
Any help on this?
Sample Data:
Input
report =
{
[HoursWorked: 1.0, HoursRate:10],
[HoursWork:2.0, HoursRate:15]
}
Expected Output
Dictioary = {Key:HoursWorked Value: 3.0,Key:HoursRate Value:25}
Dictionary<string, double> dictionary = new[] { "HoursWorked", "HoursRate" }
.ToDictionary(k => k, v => collections
.SelectMany(x => x)
.Sum(y => (double)y.GetType().GetProperty(v).GetValue(y)));
Where 'collections' is your collection of lists.
Obviously totally type unsafe and will fall down very easily!
I would argue that a much better pattern for this, as opposed to using reflection, would be to write a method or interface that will return the correct double value given the string key.
class someObject
{
public int workingHours { get; set; }
public int hourRate { get; set; }
}
You can create a common list from all list.
List<SomeObject> lst = new List<SomeObject>();
lst.AddRange(Oldlst1);
lst.AddRange(Oldlst2);
Then you can group by based on hour rate.
var n = lst.GroupBy(x=>x.hourRate);
And then you can create a dictionary.
var m=n.ToDictionary(x=>x.Key, x=>x.Sum(y=>y.workingHours));
Here in m you will get hourRate and in value you will get sum of working hour.
I have two classes:
public GeneralClassName
{
public GeneralClassName ()
{
SpecificList = new List<OtherClass>();
}
public string StringValue;
public string OtherStringValue;
public List<OtherClass> SpecificList;
}
and
public OtherClass
{
public string Name;
public string Number;
}
After a JSON deserialization I obtain a nice List<GeneralClassName>, the result I want is a Dictionary<string, int> whose value is the sum of the variabiles "Number" inside List<OtherClass> inside List<GeneralClassName>, while the key is the variabile Name.
In other words I'd like to sum Number grouping by Name.
Now, the only thing that came across my mind is a nested foreach, something like that:
Dictionary<string, int> resultDictionary = new Dictionary<string, int>();
foreach(List<OtherClass> listOtherClass in bigListGeneralClass.Select(x => x.SpecificList))
{
foreach(OtherClass otherClass in listOtherClass)
{
int value = 0;
if(resultDictionary.ContainsKey(otherClass.Name))
{
resultDictionary[otherClass.Name] += otherClass.Number;
}
else
{
resultDictionary.Add(otherClass.Name, otherClass.Number);
}
}
}
While this solution seems to work well, I don't like it at all.
Is there a more clean way to find this result? Maybe through a nice LINQ query?
As you don't use any information from the GeneralClassName you can use SelectMany to flatten your list. This flat list of OtherClass instances is than grouped by the Name property. Finally, the list of groups is transformed into a dictionary with the key of the group (aka the Name property) being the key of the new property and the value being the sum of all Number values in that group:
var result = bigListGeneralClass.SelectMany(x => x.SpecificList)
.GroupBy(x => x.Name)
.ToDictionary(x => x.Key,
x => x.Sum(y => y.Number));
This code assumes that OtherClass.Number is in fact an int not a string. This assumption is also used in your sample code with the loop.
If this assumption is not correct, change y.Number to int.Parse(CultureInfo.InvariantCulture, y.Number).
Note: This will throw an exception if any of the numbers can't be parsed, so you might want to make sure beforehand that all contain valid numbers.
Try this:
Dictionary<string, int> result =
bigListGeneralClass.SpecificList.GroupBy(sl => sl.Name)
.ToDictionary(group => group.Key, group => group.Sum(x => Int32.Parse(x.Number)));