Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts

Thursday, August 16, 2012

KeyValue pair/Dictionary with duplicate keys

Very recently for my development purpose I need to use Dictionary. And it works very nicely. But problem occurred when requirement changes and face a scenario that duplicate key's are needed to handle in Dictionary which is not possible. So I had written a custom class to handle this problem,please suggests me if there is any better idea.

Examble:

public class KeyValuePair
{
public string Key { get; set; }
public int Value { get; set; }
public string HdValue { get; set; }

public KeyValuePair(string key, int value, string hdValue)
{
this.Key = key;
this.Value = value;
this.HdValue = hdValue;
}
}

Insert Data:
List<KeyValuePair> listKeyValuePair= new List<KeyValuePair>();
listKeyValuePair.Add(new KeyValuePair("TAX",2,"Income Tax"));
listKeyValuePair.Add(new KeyValuePair("TAX",4,"Vatlue added Tax"));
listKeyValuePair.Add(new KeyValuePair("PORT",9,"Vehicle Test"));


Sort Data:
List<KeyValuePair> listSorted = listKeyValuePair.OrderByDescending(x => x.key).ToList();


Filter Data:
var filteredData = listKeyValuePair.where(keyValue=> string.Compare(keyVaue.Key,"TAX")==0).ToList();
if(filteredData.Count > 0)
{
//Do something
}

Friday, February 10, 2012

How to convert DataTable to generic List

I have discussed about conversion of DataTable to Generic List<t>. We can do it in various way. I want to share with you some of them....

Solution 1:
DataTable dt = CreateDataTable();
List<datarow> list = new List<datarow>();
foreach (DataRow dr in dt.Rows)
{
list.Add(dr);
}

Solution 2:
DataTable table = new DataTable {
Columns = {
{"Foo", typeof(int)},
{"Bar", typeof(string)}
}
};
for (int i = 0; i < 5000; i++) {
table.Rows.Add(i, "Row " + i);
}

List<T> data = new List<t>(table.Rows.Count);
foreach (DataRow row in table.Rows) {
data.Add(new T((int)row[0], (string)row[1]));
}

Solution 3:
Using Linq/lamda expression. It return data in List<t>.
List<string> list =dataTable.Rows.OfType<datarow>().Select(dr => dr.Field<string>(0)).ToList();

Solution 4:
Using Linq/lamda expression.
List<employee> list= new List<employee>();
list= (from DataRow row in dt.Rows
select new Employee
{
FirstName = row["ColumnName"].ToString(),
LastName = row["ColumnName"].ToString()

}).ToList();


Solution 5:
Using Linq/lamda expression.
List<t> target = dt.AsEnumerable()
.Select(row => new T
{
// assuming column 0's type is Nullable<long>
ID = row.Field<long?>(0).GetValueOrDefault()
Name = String.IsNullOrEmpty(row.Field<string>(1))
? "not found"
: row.Field<string>(1)
})
.ToList();


Solution 6:
Using Linq/lamda expression. All are return array of datarow in List<t>.

List<datarow> list1= dataTable.Select().ToList();
List<datarow> list2= dataTable.Rows.Cast<datarow>().ToList();
List<datarow> list3 = dataTable.AsEnumerable().ToList();
List<datarow> list4 = new List<datarow>(dataTable.select());

Here result will return all rows of datatable, as an array of datarows, and the List constructor accepts that array of objects as an argument to initially fill our List<datarow> with.

Solution 7:
Using reflection PropertyInfo class.

sealed class Tuple<T1, T2>
{
public Tuple() {}
public Tuple(T1 value1, T2 value2) {Value1 = value1; Value2 = value2;}
public T1 Value1 {get;set;}
public T2 Value2 {get;set;}
}


public static List<T> Convert<T>(DataTable table)
where T : class, new()
{
List<Tuple<DataColumn, PropertyInfo>> map =
new List<Tuple<DataColumn,PropertyInfo>>();

foreach(PropertyInfo pi in typeof(T).GetProperties())
{
ColumnAttribute col = (ColumnAttribute)
Attribute.GetCustomAttribute(pi, typeof(ColumnAttribute));
if(col == null) continue;
if(table.Columns.Contains(col.FieldName))
{
map.Add(new Tuple<DataColumn,PropertyInfo>(
table.Columns[col.FieldName], pi));
}
}

List<T> list = new List<T>(table.Rows.Count);
foreach(DataRow row in table.Rows)
{
if(row == null)
{
list.Add(null);
continue;
}
T item = new T();
foreach(Tuple<DataColumn,PropertyInfo> pair in map) {
object value = row[pair.Value1];
if(value is DBNull) value = null;
pair.Value2.SetValue(item, value, null);
}
list.Add(item);
}
return list;
}

Solution 8:
Another class using reflection PropertyInfo class.

public List<T> ConvertTo<T>(DataTable datatable) where T : new()
    {
        List<T> Temp = new List<T>();
        try
        {
            List<string> columnsNames = new List<string>();
            foreach (DataColumn DataColumn in datatable.Columns)
                columnsNames.Add(DataColumn.ColumnName);
            Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
            return Temp;
        }
        catch
        {
            return Temp;
        }

    }
    public T getObject<T>(DataRow row, List<string> columnsName) where T : new()
    {
        T obj = new T();
        try
        {
            string columnname = "";
            string value = "";
            PropertyInfo[] Properties;
            Properties = typeof(T).GetProperties();
            foreach (PropertyInfo objProperty in Properties)
            {
                columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
                if (!string.IsNullOrEmpty(columnname))
                {
                    value = row[columnname].ToString();
                    if (!string.IsNullOrEmpty(value))
                    {
                        if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
                        {
                            value = row[columnname].ToString().Replace("$", "").Replace(",", "");
                            objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
                        }
                        else
                        {
                            value = row[columnname].ToString().Replace("%", "");
                            objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
                        }
                    }
                }
            }
            return obj;
        }
        catch
        {
            return obj;
        }
    }


Hopefully it will help other developers.

Tuesday, February 7, 2012

Compare to List using C# and LINQ

LINQ offers developers a lot of useful features by which developers can solve more complex solution in a easy way. Today our discussion about comparison of two lists or collections.

Sample code 1:

static void Main(string[] args)
{
List strList1 = new List{"Jack","And","Jill","Went","Up","The","Hill"};
List strList2 = new List{"Jack", "And", "Jill", "Went", "Down", "The", "Hill"};

Console.WriteLine("Except result ...........");
var lstExcept = strList2.Except(strList1);
foreach (var variable in lstExcept)
{
Console.WriteLine(variable);
}

Console.WriteLine("Insect result ...........");
var lstInsect = strList2.Intersect(strList1);
foreach (var variable in lstInsect)
{
Console.WriteLine(variable );
}

Console.WriteLine("Union result ...........");
var lstUnion = strList2.Union(strList1);
foreach (var variable in lstUnion)
{
Console.WriteLine(variable );
}
Console.ReadLine();
}

Output:



Note that if you want to, say, ignore case:

List except = listA.Except(listB, StringComparer.OrdinalIgnoreCase);
You can replace the last parameter with an IEqualityComparer of your choosing.

You can get more information from here.

Sample code 2:
In sample code 1 just showing simple implementation. Now showing some more complex implementation.

This solution produces a result list, that contains all differences from both input lists. You can compare your objects by any property, in my example it is ID. The only restriction is that the lists should be of the same type:

var DifferencesList = ListA.Where(x => !ListB.Any(x1 => x1.id == x.id))
.Union(ListB.Where(x => !ListA.Any(x1 => x1.id == x.id)));

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...