C#

【C#】Linqラムダ式事例集

More than 3 years have passed since last update.

データがあるかチェックする


C#

String searchAuthor = "John Grisham";

bool contains = tbl.AsEnumerable()
.Any(row => searchAuthor == row.Field<String>("Author"));

同じ意味


C#


DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
// do something...
}


indexの列を追加する


C#

var result =  query.AsEnumerable().Select((x, index) => new { index,x.Id,x.FirstName});


同じ意味


C#

int i = 1;

var query = from u in dbReport.Users
join p in dbReport.Physicans on u equals p.User
let Rank = i++
select new
{
Rank.ToString(),
u.Id,
u.FirstName,
...
};


where句の複数指定


C#

TotalEatin = Data.kassaOrders.AsEnumerable().Where(x => x.Field<bool>("btwticket") && !x.Field<bool>("terugname") && !x.Field<bool>("teruggenomen"))

.SelectMany(x => Data.orderDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("serial") && !d.Field<bool>("takeout")))
.Sum(x => x.Field<decimal>("price"));

TotalEatin += Data.kassaOrders.AsEnumerable().Where(x => x.Field<bool>("btwticket") && !x.Field<bool>("terugname") && !x.Field<bool>("teruggenomen"))
.SelectMany(x => Data.orderDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("serial") && !d.Field<bool>("takeout")))
.SelectMany(x => Data.MenuDetails.AsEnumerable().Where(d => d.Field<int>("orderid") == x.Field<int>("orderid")))
.Sum(x => x.Field<decimal>("prijs"));


データの更新


C#

var dt = new System.Data.DataTable("tmp");

dt.Columns.Add("col1", typeof(string));
dt.Columns.Add("col2", typeof(string));

var row = dt.NewRow();
row["col1"] = "A01";
row["col2"] = "B01";
dt.Rows.Add(row);

row = dt.NewRow();
row["col1"] = "A02";
row["col2"] = "B02";
dt.Rows.Add(row);

row = dt.NewRow();
row["col1"] = "A03";
row["col2"] = "B03";
dt.Rows.Add(row);

dt.AsEnumerable().Where(r => r.Field<string>("col1") == "A02").Select(r => r["col2"] = "hoge").ToList();