4

I need some help filtering some data. I've got an object class with three properties. The collection of objects I've got can have many matches of the first property, Point3d. From that collection of matches I need to see if the second property has unique values, Tag. Finally, I need to be able to identify the objects whos Point3d match, and Tags are different, using the third property, it's Id (which is always unique).

class pmatch { public string Point3d { get; set; } public string Tag { get; set; } public string Id { get; set; } } 

An example of what i'm looking for would be:

List<pmatch> dataset = new List<pmatch> { new pmatch { Point3d = "1, 1, 1", Tag = "5", Id = "123" }, new pmatch { Point3d = "1, 1, 1", Tag = "6", Id = "124" }, new pmatch { Point3d = "1, 1, 2", Tag = "7", Id = "125" }, new pmatch { Point3d = "1, 1, 2", Tag = "7", Id = "126" } }; 

I need to be able to identify Id's 123 and 124, as their Point3ds match, but their Tags do not. I've been able to identify these instances using LINQ:

var result = datalist.GroupBy(item => item.Point3d, item => item.Tag); foreach (var group in result) { Console.WriteLine(group.Key); var uniqueTags = group.Distinct().ToList(); if (uniqueTags.Count > 1) { Console.WriteLine("Found mismatched tags"); foreach (string Tag in group) { Console.WriteLine(" {0}", Tag); } } } 

However these results do not give me the Id, so I can not access the object I have identified. How do I get these results along with the Id, or the pmatch object itself?

1 Answer 1

5

You can accomplish the desired result like so:

var resultSet = dataset.GroupBy(item => item.Point3d) .Where(group => group.Select(item => item.Tag) .Distinct() .Count() > 1) .ToDictionary(item => item.Key, item => item.ToList()); 

This will identify Id's 123 and 124, as their Point3ds match, but their Tags do not and also resultSet is of type Dictionary<string, List<pmatch>> so you have access to all the properties of the pmatch object.

Sign up to request clarification or add additional context in comments.

4 Comments

This works great, thank you. How do I learn to understand Linq like this?
@Treefingers you're more than welcome :). I guess it all comes down to practice. maybe I can recommend going through the tutorials on this site dotnetperls.com/linq and go through each extension method tutorial individually whenever you have time and see how it goes.
Nice solution! @Treefingers You also can learn by paying attention on the intelissense of the visual studio. It can be useful to learn linq, reflection, and etc..
Most of my advanced LINQ knowledge comes from looking up answers on Stack. After you look up so many, you start to see ways to apply the techniques others use for your own solutions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.