Calculation using LINQ

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have a List<MyObject> where MyObject has two properties: N (int) and
Weight (int).

In this list only the N is defined for each tag.

I want to calculate the Weight for each MyObject in the list, as
follows:

Weight of MyObject = N of Tag / Maximum N of all MyObject in list

How can I do this using a Linq expression?

Thanks,
Miguel
 
Hi shapper,

It can be like this:

var secondList = from item in list select new MyObject
{
N = item.N,
Weight = item.N/ (from aggitem in list select item.N).Max() // or simple
list.Max(l => l.N)
};

Regards, Alex Meleta
mailto:[email protected]; blog:devkids.blogspot.com
 
Alex Meleta said:
It can be like this:

var secondList = from item in list select new MyObject
{
N = item.N,
Weight = item.N/ (from aggitem in list select item.N).Max() // or simple
list.Max(l => l.N) };

This obviously works, but it will recalculate list.Max for every item in the
list. Better to calculate it outside the LINQ expression and then reuse the
stored value inside.
 
shapper said:
Hello,

I have a List<MyObject> where MyObject has two properties: N (int) and
Weight (int).

In this list only the N is defined for each tag.

I want to calculate the Weight for each MyObject in the list, as
follows:

Weight of MyObject = N of Tag / Maximum N of all MyObject in list

How can I do this using a Linq expression?

You don't. LINQ takes one sequence as input, and produces another new
sequence at the output. From your description, you want to mutate the values
in-place, and within the same List - in which case foreach is the best tool
for the job here (though you could still use Enumerable.Max() to calculate
the maximum N first).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top