Friday, October 24, 2008

Learning and implement LINQ concepts with .NET 2.0

In sql, we familiar to use key like "select", "where", "order by", and more.

Now, i'am try to implement that into .NET 2.0

Example:

col1 col2
Ronald True
Eriawan True
Nicko False

How to get col1 members where col2 value is True ?

SQL-Query

SELECT [col1] FROM [tbl] WHERE [col2] = 'True' ;

.NET 2.0

//Give condition
IEnumerable<DataRow> iEnumDataRow= csQuery.Where<DataRow>(Datarow [], delegate(DataRow row) { return Convert.ToBoolean(row[col2]) ; }) ;
 
//Get Data
IEnumerable<string> iEnumString = csQuery.Select<DataRow, string>(iEnumDataRow, delegate(DataRow row) { return row[col1].ToString(); });
 
//View Data
List<string> listString = new List<string>(iEnumString);
How it running successfull?

Lets make the simple class, for example csQuery.


public delegate TResult Func<TSource, TResult>(TSource arg);
 
public static class csQuery
{
    public static IEnumerable<TSource> Where<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        if (source == null)
            throw new ArgumentNullException(source.GetType().ToString()); 
 
        if (predicate == null)
            throw new ArgumentNullException(predicate.GetType().ToString()); 
 
        return WhereIterator<TSource>(source, predicate);
    }
 
    private static IEnumerable<TSource> WhereIterator<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        foreach (TSource var in source)
        {
            if (predicate(var))
                yield return var;
        }
    }
 
    public static IEnumerable<TResult> Select<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector)
    {
        if (source == null)
            throw new ArgumentNullException(source.GetType().ToString()); 
 
        if (selector == null)
            throw new ArgumentNullException(selector.GetType().ToString()); 
 
        return SelectIterator<TSource, TResult>(source, selector);
    } 
 
    private static IEnumerable<TResult> SelectIterator<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector)
    {
        foreach (TSource var in source)
        {
            yield return selector(var);
        }
    }
} 

No comments:

Post a Comment