 How do we get max value after converting a negative number [Answered]RSS

3 replies

Last post May 17, 2017 09:20 AM by gani7787

• How do we get max value after converting a negative number

Hi,
I am new to linq.
I want to fetch max column value from "n" rows.
This should happen after converting my negative number to positive number.
For example,
Empno. Sub1. Sub2
------------ -------- --------
101 -87 -94
101 -95 -86
101 -97 -98.

First i want to convert negative to positive number.
Second, after converting into positive number, then i want
to get maximum value of sub1 and sub2.
Sub1 : 97
Sub2 : 98

How do we write linq query in c#.net.

• Re: How do we get max value after converting a negative number

Hello gani7787,

for your first problem you need to multiply each value by 100 in your case

for other problem here is it perhpas a solution :

``` protected void Page_Load(object sender, EventArgs e)
{
List<myItems> items = new List<myItems>();
myItems it = new myItems();
it.ID = 1;
it.Number1 = 0;
it.Number2 = 150;

//
it = new myItems();
it.ID = 1;
it.Number1 = 90;
it.Number2 = 100;

//
var query = items.GroupBy(r => r.ID)
.Select(grp => new
{
ID = grp.Key,
Max1 = grp.Max(t => t.Number1),
Max2 = grp.Max(t => t.Number2)
});
}
}

public class myItems
{
public int ID { get; set; }
public int Number1 { get; set; }
public int Number2 { get; set; }
}```

Thanks for your time and your knowledge that's great to find any help here ..
• Re: How do we get max value after converting a negative number

May 17, 2017 07:13 AM|Zhi Lv - MSFT|LINK

Hi gani7787,

You could use the Math.Abs method to convert the number, then use the Max method to get the max number.

Code as below:

```            List<myItems> mitems = new List<myItems>();
mitems.Add(new myItems() { Empno = 101, Sub1 = -87, Sub2 = -94 });
mitems.Add(new myItems() { Empno = 101, Sub1 = -95, Sub2 = -86 });
mitems.Add(new myItems() { Empno = 101, Sub1 = -97, Sub2 = -98 });

var query = mitems.GroupBy(r => r.Empno)
.Select(grp => new { empno = grp.Key, Max1 = grp.Max(t => Math.Abs(t.Sub1)), Max2 = grp.Max(t => Math.Abs(t.Sub2)) });
foreach (var l in query)
{
Response.Write(string.Format("Sub1:{0},Sub2:{1}", l.Max1, l.Max2));
}```

Best regards,
Dillion

MSDN Community Support