LINQ: Distinct values

Are you trying to be distinct by more than one field? If so, just use an anonymous type and the Distinct operator and it should be okay: var query = doc.Elements(“whatever”) .Select(element => new { id = (int) element.Attribute(“id”), category = (int) element.Attribute(“cat”) }) .Distinct(); If you’re trying to get a distinct set of values … Read more

What are the benefits of a Deferred Execution in LINQ?

The main benefit is that this allows filtering operations, the core of LINQ, to be much more efficient. (This is effectively your item #1). For example, take a LINQ query like this: var results = collection.Select(item => item.Foo).Where(foo => foo < 3).ToList(); With deferred execution, the above iterates your collection one time, and each time … Read more

Is it possible to Pivot data using LINQ?

Something like this? List<CustData> myList = GetCustData(); var query = myList .GroupBy(c => c.CustId) .Select(g => new { CustId = g.Key, Jan = g.Where(c => c.OrderDate.Month == 1).Sum(c => c.Qty), Feb = g.Where(c => c.OrderDate.Month == 2).Sum(c => c.Qty), March = g.Where(c => c.OrderDate.Month == 3).Sum(c => c.Qty) }); GroupBy in Linq does not work … Read more

LINQ equivalent of foreach for IEnumerable

There is no ForEach extension for IEnumerable; only for List<T>. So you could do items.ToList().ForEach(i => i.DoStuff()); Alternatively, write your own ForEach extension method: public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action) { foreach(T item in enumeration) { action(item); } }

Convert this sql command to c# linq

var query = ( from v in dbContext.UnitFeatureValue join u in dbContext.Unit on v.FK_Unit_ID equals u.ID join t in dbContext.FeatureTitle on v.FK_FeatureTitle_ID equals t.ID where v.FK_Unit_ID == 15 && t.canMoreSelect == 1 select new { v.FK_Unit_ID, u.unitNumber, u.unitTitle, t.featureTitleName, }).Distinct();