Friday, November 5, 2010

converting to LINQ

1) Change a for loop to LINQ:
before:
for (int i = 0; i < questions.answers.Count; i++)
{
if (questions.answers[i] == 0 && string.IsNullOrEmpty(questions.answers.Text))
{
questionAnswered = false;
break;
}
}

after:
if (questions.answer.Any(t => t == 0 && string.IsNullOrEmpty(questions.answers.Text)))
{
questionAnswered = false;
}


2) Convert a list of type T to a list of type U:
List<String> strList="....";
List<Object> objList= strList.Cast<object>().ToList();


3) get back a list of people with first name started with Q; last name contains "Cute", and the average and the minimum ages
public class person
{
public string FirstName;
public string LastName;
public int Age;
}

List<person> people = new List<person>{
new person {FirstName="DD", LastName="Cute", Age=35}
new person {FirstName="QQ", LastName="NotCute", Age=40}
new person {FirstName="Qing", LastName="Cool", Age=38}
}
"

IEnumerable<person> peopleQ=people.Where(p=>p.FirstName.StartWith("Q"));

IEnumerable<person> peopleCute=people.Where(p=>p.LastName.Contains("Cute"));

int MinAge=people.Min(p=>p.Age());

int AverageAge=people.Average(p=>p.Average());

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. System.Linq can be slow comparing to the old-fashioined compiled T-SQL. Look into compiled System.Data.Linq and PLinq (Parallel Linq) if you encounter performance issue.

    ReplyDelete