Reputation: 4786
I have a list of objects(FilesInfo) that contain objects(LanguageInfo). LanguageInfo is an object that contains further objects for LanguageName and LanguageId. The LanguageName and LanguageId is also an object, that (finally) contains a string value.
I want to group the list of files by the language. This doesn't work (I suppose a matter of by value/reference comparing magic):
var languageGroupings = data.FilesList.GroupBy(ufi => ufi.LanguageInfo);
(although this is what I am essentially trying to achieve)
This does:
var languageGroupings = data.FilesList.GroupBy(ufi => ufi.LanguageInfo.LanguageName.Value);
Now, the issue is that I don't know whether the LanguageInfo will contain LanguageName, or LanguageCode (or one of other similar properties, ClientLanguageName, ClientLanguageCode) - which is why I basically want to group the files based on all of the properties values nested in LanguageInfo.
How do I do that?
These are the (minimized) classes:
public class UniversalLanguageInfo
{
public int UniversalLanguageInfoId { get; set; }
public UniversalDataElement LanguageCode { get; set; }
public UniversalDataElement LanguageId { get; set; }
public UniversalDataElement LanguageName { get; set; }
public UniversalDataElement ClientLanguageCode { get; set; }
public UniversalDataElement ClientLanguageName { get; set; }
}
public class UniversalDataElement
{
public string Value { get; set; }
public DataFormats DataSource { get; set; }
public string OriginalName { get; set; }
public bool IsExcluded { get; set; }
}
public class UniversalFileInfo
{
public virtual UniversalDataFormat UniversalDataFormat { get; set; }
public UniversalLanguageInfo LanguageInfo { get; set; }
public UniversalDataElement FileName { get; set; }
public UniversalDataElement Id { get; set; }
public UniversalWordcount Wordcount { get; set; }
}
Upvotes: 0
Views: 693
Reputation: 21729
Implement Equals(object)
and Equals<T>
for your UniversalLanguageInfo
and UniversalLanguageElement
classes. When you do the GroupBy()
you will get the results you're looking for.
In your implementations of these methods, you can choose the level to which they are "equal". In the case you describe, that's a "deep equals", which means you need to implement equals for the entire graph except for the objects in that graph that you're sure have an Equals
that is suitable. At each level call the Equals
of all the children.
As meJustAndrew below suggests, you will have to implement GetHashCode()
because that is good practice. Gian Paolo suggests going the comparer route, which is especially useful if you aren't able to modify the classes in your object graph or don't want general equality to be universally available.
Upvotes: 1