Apr 8, 2013

Custom type comparing

You have custom type EditorColumn:

public class EditorColumns
{

        public bool IsSelected { get; set; }
        public string FieldName { get; set; }
        public int? OrderId { get; set; }

}

I want to do lambda expression that checks whether MyCollection that is collection of EditorColumn's contains seleted MyEditorColumn of type EditorColumns.
LINQ lambda for this is:   Contains

What is equality criteria for this?
How do you define that MyEditiorColumn has its matches in collection?
Since this is not value type by default .NET will use type reference.

Let's say that two EditorColumn's are equal if their fieldname's exactly match.

This has to be  designed into our EditorColumn like this:


internal class FieldNameComparer : IEqualityComparer<EditorColumn>
        {
            public bool Equals(EditorColumn x, EditorColumn y)
            {
                return x.FieldName.ToLowerInvariant() == y.FieldName.ToLowerInvariant();
            }

            public int GetHashCode(EditorColumn obj)
            {
                return 0;
            }
        }

There is no rule but I suggest that above class is placed inside EditorColumn type def.

Now we can write something like this:

var optionalDefs = defaultColumns.Where(dc => !userDefEdCols.Contains<EditorColumn>(dc,new EditorColumn.FieldNameComparer())).ToList<EditorColumn>();


Here is some more info:

http://www.code-magazine.com/Article.aspx?quickid=100083

No comments:

Post a Comment