Search

Showing posts with label Generics. Show all posts
Showing posts with label Generics. Show all posts

Dec 8, 2008

Querying Selected Items From ListItemCollection Using LINQ

Working with ListItemCollection is general practices and getting single value for that it's like child's play. What if you need the list of items which are selected?

I am sure you probably use foreach loop something like

List<ListItem> selectedList = new List<ListItem>();
foreach(ListItem li in cbList.Items)
{
if (li.Selected)
selectedList.Add(li);
}

Or advance user use the functionality of C#2.0 using yield keyword

private IEnumerable<ListItem> GetSelectedItems(ListControl listControl)
{
foreach (ListItem itm in listControl.Items)
{
if (itm.Selected)
yield return itm;
}
}
.
.
.
.
.
.
{
IEnumerable<ListItem> selectedList = new List<ListItem>();
selectedList = GetSelectedItems(cbList);
}
And now using LINQ C#3.0

var selectedItems =
from li in cbList.Items.Cast<ListItem>()
where li.Selected == true
select li;

The only difference is the Cast, we need to make ListItemCollection generic so we can use it in LINQ query.

And now lets see using Lambda Expression C#3.0

List<ListItem> selectedItems =
cbList.Items.Cast<ListItem>()
.Where(item => item.Selected == true).ToList();

Here also we did cast to get the extension method Where. And in Where condition we write the lambda expression instead of anonymous delegate function.

We can even write extension method on base class ListControl so we can have selected items for all the list control. Lets write one extension method on ListControl

public static List<ListItem> SelectedItems(this ListControl lc)
{
List<ListItem> selectedItems =
lc.Items.Cast<ListItem>()
.Where(item => item.Selected == true).ToList();
return selectedItems;
}

And get the selected items using our extension method we will just call the SelectedItems method.

CheckBoxList cbList = new CheckBoxList();
cbList.SelectedItems();

Aug 12, 2008

How to sort generic collection

Hi all,

We will now sort generic collection. For this we need to create one comparere class which inherits IComparer<T> and implement Compare method, where T is your class object. Compare method is responsible to compare tow object and based on the result sorting will be done.

public class TestSortComparere : IComparer<TestSort>
{
public TestSortComparere() { }

#region IComparer<TestSort> Members

public int Compare(TestSort x, TestSort y)
{
return string.Compare(x.a, y.a);
}

#endregion
}

Now lets call Sort method.

List<TestSort> MyObjList = new List<TestSort>();
MyObjList.Add(new TestSort("Imran"));
MyObjList.Add(new TestSort("Dipak"));
MyObjList.Add(new TestSort("Sachin"));
MyObjList.Add(new TestSort("Darshan"));
MyObjList.Add(new TestSort("Gaurav"));

MyObjList.Sort(new TestSortComparere());

You can see the sorted order when you iterate MyObjList

foreach (TestSort testSort in MyObjList)
Console.Write(testSort.strTest + Environment.NewLine);
//OUTPUT
/*
Darshan
Dipak
Gaurav
Imran
Sachin
*/

We can change the sort line using Anonymous delegate. Lets see how, its only in single line!!!!.

MyObjList.Sort(delegate(TestSort x, TestSort y) { return string.Compare(x.strTest, y.strTest); });

Aug 8, 2008

Inserting value of Collection into Database

We always require thing like this, when you need to Insert list of object at the same time with single database operation.

Generally what we are doing is inserting individual object from front end, which is not good idea; in case where you have 100 of object needs to be inserted same time.

With the new feature Extension Method included in C# 3.0 and the XML datatype provided in SQL Server 2005, with combining these two we can achive the goal with less affort in terms of traffic and compactness of code.

I posted code on Code Project, it has description of each important phase you can download and customize according your need.

Mar 14, 2008

Cannot convert type 'System.Collections.Generic.List<

I have one problem while working with Generic collection. I am returning the generic collection of base class, which at the end assigned to child class.


List<Child> childs = SelectAll();

Here is the defination of SelectAll();


public override List<MyParent> SelectAll()

While doing this I got an error....

Cannot implicitly convert 'System.Collections.Generic.List<MyParent>' to 'System.Collections.Generic.List<Child>'

Because, the returning collection is of MyParent and I need to store it into collection of Child.

Here is the solution.

Generic collection List<> provider one Generic method called ConvertAll

ConvertAll: Converts the elements in the current List<(Of <(T>)>) to another type, and returns a list containing the converted elements.

Here is the code,

List childs = SelectAll().ConvertAll<child>(ParentToChild);

and here is the ParentToChild method.

public static Child ParentToChild(MyParent myParent)
{
return (Child)myParent;
}


Read more..

Jan 21, 2008

Passing lists to SQL Server 2005 with XML Parameters

We frequently have requirement like

Passing IDs in comma saperated value to the sql server for further processing.

Generally what we do is just create loop and get the value from it and ...

But SQL 2005 comes up with XQuery. Using this you can easly pass such type of data also some complex thing too.

For example...

DECLARE @productIds xml
SET @productIds ='<Products><id>3</id><id>6</id><id>15</id></Products>'


SELECT ParamValues.ID.value('.','VARCHAR(20)')FROM @productIds.nodes('/Products/id') as ParamValues(ID)

Which gives us the following three rows:

3
6
15

Read more..

Feb 15, 2007

Compare two objects!!!


Use IComparer Generic Interface.

This interface provides


public int Compare(object x, object y)

you overiddes this method and implement yours, so simple right?


Example:


public class MyComparer : IComparer
{
public MyComparer() { }

public int Compare(object x, object y)
{
return DateTime.Compare(((MyClass)x).EntryDate, ((MyClass)y).EntryDate);
}

}
A delicious related to this topic!