Czy da się podany kod zapisać cały w LINQ bez zbędnych ceregieli ?

0

Czy da się poniższy kod zapisać cały w LINQ bez zbędnych ceregieli ?

var subItemsToUpdate = context.SubscriptionItems.Where(x => x.ProductId == id && x.SubscriptionId == subscriptionId).ToList();
int counter = 0;
foreach (var subItem in subscriptionItems.Where(x => x.SubscriptionItemId == id))
{
	for (int i = 0; i < subItem.LicenseCount; i++)
	{
		subItemsToUpdate[counter].LicensePriceBrutto = subItem.LicensePriceBrutto;
		subItemsToUpdate[counter].StartDate = subItem.ActivationDate;
		subItemsToUpdate[counter].ExpiredDate = subItem.ExecutionDate;
		counter++;
	}
}
context.SaveChanges();
0

Generalnie nie polecam walnąć tego 1 chainem, ale jak tak bardzo chcesz, to wrzucę coś.

A tak lepiej, to samo SelectMany + pętla będą ok

var dates = new List<DateTime> { DateTime.Now, DateTime.Now.AddHours(5) };

var subs = new List<subscriptionItems>
{
	new subscriptionItems
	{
		Id = 1,
		Items = new List<License>{ new License()}
	}, 
	new subscriptionItems
	{
		Id = 1,
		Items = new List<License>{ new License()}
	},
	new subscriptionItems
	{
		Id = 2,
		Items = new List<License>{ new License()}
	}
};

subs
	.Where(x => x.Id == 1)
	.SelectMany(x => x.Items)
	.Select((item, index) => new { item, index })
	.ToList()
	.ForEach(x =>
	{
		x.item.EndDate = dates[x.index];
		x.item.StartDate = dates[x.index];
	});

foreach (var item in subs)
{
	foreach (var sub_item in item.Items)
	{
		Console.WriteLine(sub_item.StartDate);
		Console.WriteLine(sub_item.EndDate);
	}
public class subscriptionItems
{
	public int Id { get; set; }
	public List<License> Items { get; set; } = new List<License>();
}

public class License
{
	public DateTime StartDate { get; set; }
	public DateTime EndDate { get; set; }
}
3
balti napisał(a):

Czy da się poniższy kod zapisać cały w LINQ bez zbędnych ceregieli ?

Nie, bo LINQ to język zapytań, a nie modyfikacji.
Nie walcz z językiem próbując robić jakieś dziwne haki, a ten, kto potem będzie to czytał, będzie Ci wdzięczny.

2

@somekind:

ForEach to nie jest LINQ

@balti:

Czy dałoby się użyć jakoś ForEach, ale bez konwersji do ToList ? :)

subs
.Where(x => x.Id == 1)
.SelectMany(x => x.Items)
.Select((item, index) => new { item, index })
.Where(x =>
{
	x.item.EndDate = dates[x.index];
	x.item.StartDate = dates[x.index];
	return true;
})
.ToArray(); // evaluation, aby podglądnąć wartości w debuggerze :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1