Replace List<T>.Where() with your own "Where" to understand Func<T>

by sunil ravulapalli /1. March 2014 06:25 /c# /Comments (0)
class Program
{
	static void Main(string[] args)
	{
		List<string> names = new List<string> {
											"mickey",
											"donald",
											"goofy",												
									};

		var outnames = names.Finder(x => x == "donald");

		foreach (var name in outnames) 
		{
			Console.WriteLine(name);
		}
		Console.ReadLine();            
	}        
}

public static class MyExtentions
{
	public static IEnumerable<string> Finder(this IEnumerable<string> strings, Func<string, bool> predicate)
	{
		foreach (var str in strings)
		{
			if (predicate(str) == true)
				yield return str;
		}
	}
}

Enumerable.Range Example

by sunil ravulapalli /1. March 2014 05:18 /c# /Comments (0)

 

var numbers = Enumerable.Range(1, 10);

foreach(var num in numbers)

{

	Console.WriteLine(num);

}

 

OUTPUT:

1
2
3
4
5
6
7
8
9
10

 

Sample showing how to use Action<T> in your own code

by sunil ravulapalli /28. September 2013 06:29 /c# /Comments (0)

In the below sample you can see that Action<T> can used to reuse the function Display multiple times. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var customers = new List<Customer>();

            customers.Add(new Customer { Id = 1, Name = "aaa"});
            customers.Add(new Customer { Id = 2, Name = "bbb" });
            customers.Add(new Customer { Id = 3, Name = "ccc" });

            //Display Ids
            Action<Customer> action1 = c => Console.WriteLine(c.Id);
            Display(customers, action1);

            //Display Names
            Action<Customer> action2 = c => Console.WriteLine(c.Name);
            Display(customers, action2);

            Console.ReadLine();
        }

        static void Display(List<Customer> customers, Action<Customer> action)
        {
            foreach (var c in customers)
            {
                action.Invoke(c);
            }            
        }
    }

    internal class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Example showing how you can use Func<T> in your own functions

by sunil ravulapalli /28. September 2013 06:09 /c# /Comments (0)

In the following example you can see that the Find function can re-used multiple times if we use Func<T>

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var customers = new List<Customer>();

            customers.Add(new Customer { Id = 1, Name = "aaa"});
            customers.Add(new Customer { Id = 2, Name = "bbb" });
            customers.Add(new Customer { Id = 3, Name = "ccc" });

            var result1 = Find(customers, c => c.Id == 1);
            Console.WriteLine(result1.Id + " : " + result1.Name);

            var result2 = Find(customers, c => c.Name == "ccc");
            Console.WriteLine(result2.Id + " : " + result2.Name);

            Console.ReadLine();
        }

        private static Customer Find(List<Customer> customers, Func<Customer, bool> predicate)
        {
            return customers.SingleOrDefault(predicate);
        }
    }

    internal class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Example explaining Func<T>

by sunil ravulapalli /28. September 2013 05:41 /c# /Comments (0)

Below is a simple program which shows three different ways we can pass the parameter to SingleOrDefault on a List<T>.

If essentially shows what Func<T> really is. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FuncTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var customers = new List<Customer>();

            customers.Add(new Customer { Id = 1, Name = "aaa"});
            customers.Add(new Customer { Id = 2, Name = "bbb" });
            customers.Add(new Customer { Id = 3, Name = "ccc" });

            //1
            var result1 = customers.SingleOrDefault(findFunction);
            Console.WriteLine(result1.Name);

            //2
            var result2 = customers.SingleOrDefault(delegate(Customer c)
                {
                    if (c.Id == 2)
                        return true;

                    return false;
                });
            Console.WriteLine(result2.Name);

            //3
            var result3 = customers.SingleOrDefault(c => c.Id == 3);
            Console.WriteLine(result3.Name);

            Console.ReadLine();
        }

        private static bool findFunction(Customer customer)
        {
            if (customer.Id == 1)
                return true;

            return false;
        }

    }

    internal class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

Much More Linq to Xml

by sunil ravulapalli /8. September 2011 17:52 /c# /Comments (0)
  
    100
    
    2
    
  

This is how the query looks:

WebReportData webReportData =
(
	from xml in data.Elements("xml")
	select new WebReportData
	{
		Distance = (from element in xml.Descendants("element") 
					where xml.Element("element").Attribute("name").Value == "distance" 
					select element).First().Value,
		Email = (from element in xml.Descendants("element") 
					 where xml.Element("element").Attribute("name").Value == "email" 
					 select element).First().Value,
		Education = (from element in xml.Descendants("element") 
					 where xml.Element("element").Attribute("name").Value == "education" 
					 select element).First().Value,
		Phone = (from element in xml.Descendants("element") 
					 where xml.Element("element").Attribute("name").Value == "phone" 
					 select element).First().Value
	}
).First();

The classes look like this:

public class WebReportData
{
	public string Distance { get; set; }
	public string Email { get; set; }
	public string Education { get; set; }
	public string Phone { get; set; }
}

More Linq to Xml

by sunil ravulapalli /31. August 2011 16:35 /c# /Comments (0)

  
    1
    
      
        mr
      
      
        mr2
      
    
  

  
    2
    
      
        mr
      
    
  

  
    3
    
    
  


This is how the query looks:

IEnumerable people =
from person in data.Elements("person")
select new Person
{
	id = (int)person.Element("id"),
	positions = (
				from position in person.Elements("positions").Elements("position")
				select new Position { title = position.Element("title").Value } 
			 ).ToList()
};

The classes look like this:

public class Person
{
	public int id { get; set; }
	public List positions { get; set; }
}

public class Position
{
	public string title { get; set; }
}

Linq XML samples

by sunil ravulapalli /5. November 2010 15:39 /c# /Comments (0)

Sample XML:

  
    ChapterOne-SectionOne
    ChapterOne-SectionTwo
    ChapterOne-SectionThree
    ChapterOne-SectionFour
    ChapterOne-SectionFive
  
  
    ChapterTwo-SectionOne
    ChapterTwo-SectionTwo
    ChapterTwo-SectionThree
    ChapterTwo-SectionFour
    ChapterTwo-SectionFive
  
	

Lets say, I want to print out contents of Chapter 2-Section 4:

XElement data = 
XElement.Load(Request.PhysicalApplicationPath + "book.xml");

XElement chapterElement =
     (
        from chapter in data.Elements("chapter")
        where chapter.Attribute("id").Value == "2"
        select chapter
     ).Single();


XElement sectionElement =
     (
        from section in chapterElement.Elements("section")
        where section.Attribute("id").Value == "4"
        select section
     ).Single();

Response.Write(sectionElement .Value);

(I could complicate matters and write some embedded queries, but I chose to be more readable)