Wednesday, May 16, 2012

linq orderby custom comparer

I need to orderby Customer Collection.There fore i have to write new class extending with IComparer<T> interface.

public class EntityComparer<T> : IComparer<T> where T : class
    {
        #region IComparer<T> Members

        public int Compare(T x, T y)
        {
            string valuex = string.Empty;
            string valuey = string.Empty;

            if (x is StringField && y is StringField)
            {
                valuex = GetStringFieldValue(x as StringField);
                valuey = GetStringFieldValue(y as StringField);
            }

            if (x is BasicDataField && y is BasicDataField)
            {
                valuex = GetBasicDataFieldValue(x as BasicDataField);
                valuey = GetBasicDataFieldValue(y as BasicDataField);
            }

            return Compare(valuex, valuey);
        }

        #endregion

        #region Helpers

        private string GetBasicDataFieldValue(BasicDataField field)
        {
            string value = string.Empty;

            if (null !=  field && null != field.NewValue && !string.IsNullOrEmpty(field.NewValue.Description))
            {
                value = field.NewValue.Description;
            }

            return value;
        }

        private string GetStringFieldValue(StringField field)
        {
            string value = string.Empty;

            if (null != field && !string.IsNullOrEmpty(field.NewValue))
            {
                value = field.NewValue;
            }

            return value;
        }

        private  int Compare(string x, string y)
        {
            return string.Compare(x, y, true, CultureInfo.InvariantCulture);
        }

        #endregion
    }

Then we can do our linq ordering like bellows
bomLines.OrderBy(record => record.BOMCategoryType, new EntityComparer<BasicDataField>());
Here we have to create new instance of the our Custom comparer class.
Related Posts:http://prabodha-eranga.blogspot.com/2012/04/linq-order-by-multiple.html

No comments:

Post a Comment