sarpay
7/31/2018 - 9:17 AM

Lambda Expressions

#C Lambda Expressions

Like Operator

to get all the customers from cities which start with vowels

var customers =
  from c in context.Customers 
  where EF.Functions.Like(c.City, "[aeiou]%")
  select c;

If we were to search all the 4 lettered names with 'ri' as the middle characters we could do

EF.Functions.Like(c.Name, "_ri_");

Include Child Classes

// customer id'si XXX olan insured'larin
// bagli oldugu tum policeleri getirir.
_policyManager
  .GetAll()
  .Include(p => p.Insureds)
  .Where(p => p.Insureds
    .Select(i => i.CustomerId).Contains("XXX")
  ).ToList();

Select Multiple Columns

results.Select(p => new { p.Id, text = $"{p.Id}-{p.Code}-{p.Name}"});
// -- or --
InstallmentList.Select((item, index) => new { item, index }).OrderByDescending(x => x.item.Amount)

In For Each Loop

@{
  foreach (var item in Model.InstallmentList.Select((item, index) => new { item, index }))
  {
    <tr>
      <td> @(item.index + 1) </td>
      <td> @item.item.DueDate.ToShortDateString() </td>
      <td> @item.item.Amount ₺ </td>
    </tr>
  }
}

Find Distincts

public async Task<ActionResult> ImportData(SicknessRiskySicknessImport importList)
{
  List<Distincts> distinctList = importList.GroupBy(x => x.Id).Select(x => x.FirstOrDefault()).ToList();
}

Multi-Column Grouping

paymentAccountsList.GroupBy(x => new { x.CustomerId, x.AccountHolderName });

SelectMany & Sum

var CommissionTotal = policyGroup.Where(x => x.ProposalStatus != ProposalStatus.Rejected)
                        .SelectMany(x => x.Insureds)
                        .SelectMany(x => x.Coverages)
                        .Select(x => x.Commission)
                        .DefaultIfEmpty(0).Sum()

Contains & Exists

// Create a list of parts.
List<Part> parts = new List<Part>();

// Add parts to the list.
parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
parts.Add(new Part() { PartName = "shift lever", PartId = 1634 });

// Check the list for part #1734. This calls the IEquatable.Equals method
// of the Part class, which checks the PartId for equality.
bool contains = parts.Contains(new Part { PartId = 1734, PartName = "" })
// Returns: False

// Find items where name contains "seat".
// Returns the first element that matches the conditions defined by the predicate
Part part = parts.Find(x => x.PartName.Contains("seat"));
// Returns: ID: 1434  Name: regular seat

// Check if an item with Id 1444 exists.
bool exists = parts.Exists(x => x.PartId == 1444);
// Returns: True

Count

var groupTxt = missingIdsTxt.Count(x => x == ',') > 1 ? "grupları" : "grubu";

Any

var missingRiskySicknessIds = new List<string>();
bool containsRiskySicknessId = missingRiskySicknessIds.Any(x => riskySicknessId.Contains(x));
if (!containsRiskySicknessId)
  missingRiskySicknessIds.Add(riskySicknessId);

Group & Sum

Group list by PartNumbers and Sum the Quantities to merge multiple rows into 1.

importManifestDtoList = (from l in importManifestDtoList
                         group l by l.PartNumber into MergedParts
                         select new ImportManifestDto
                         {
                             PartNumber = MergedParts.Key,
                             Quantity = MergedParts.Sum(s => s.Quantity)
                         }).ToList();

Convert List to Comma Delimited String

var rolesString = Roles.Select(r => r.RoleName).JoinAsString(", ");