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

Thursday, May 10, 2012

execute scalar function in sql server

As follows you can test your scalar function in sql server.Result holding variable type should be same as the function return type.

DECLARE @RESULT VARCHAR(2500)

EXEC @RESULT= FUNC_GET_VC_COLUMNS_ENCODED 'CO_LINE','PRI1234',0,1,1,1

PRINT @RESULT

Note:My sql server  version is 2008 R2.If you use sql server  2008 some time you might have to use schema also.

EXEC @RESULT= dbo.FUNC_GET_VC_COLUMNS_ENCODED 'CO_LINE','PRI1234',0,1,1,1