简体   繁体   中英

Issue with Group By in LinQ Query

I want to make a LinQ query against an array with and return multiple columns. I can't seem to get it working correctly, and I've tried various things.

First off, the array contains a type and a version from a table such as:

TypeID-------VersionID-------Text
1            1               "Version 1.1"
2            1               "Version 2.1"
3            1               "Version 3.1"
3            2               "Version 3.2"

This is a SQL table, and I could easily get the latest version with this query:

SELECT 
        V.*
FROM Table V
WHERE V.VersionID IN (SELECT MAX(VersionID) GROUP BY TypeID)

However, I want to do this in LinQ and it's killing me. I can't figure it out. I want all the values. Therefore:

public MyStruct
{
   public int TypeID,
   public int VersionID,
   public string Text
}

MyStruct[] array = new MyStruct[4];
array[0].TypeID = 1;
array[0].VersionID = 1;
array[0].Text = "Version 1.1";
array[1].TypeID = 2;
array[1].VersionID = 1;
array[1].Text = "Version 2.1";
array[2].TypeID = 3;
array[2].VersionID = 1;
array[2].Text = "Version 3.1";
array[3].TypeID = 3;
array[3].VersionID = 2;
array[3].Text = "Version 3.2";

Now, I want a resultant array that only has three elements containing Version 1.1, Version 2.1, and Version 3.2. Since Version 3.1 is an "older version", I want to ignore it.

My LinQ is like this:

var myArrayQuery = from arr in array
group arr by arr.TypeID into arrGroup
select new
{
   TypeID = arrGroup.Key,
   VersionID = (int)arrGroup.Max(mx=>mx.VersionID)
   // -- GET THE TEXT HERE ---
};

I can't figure out how to get the text!

I have tried:

var myArrayQuery = from arr in array
group arr by new{ arr.TypeID, arr.VersionID, arr.Text} into arrGroup
select new
{
   TypeID = arrGroup.TypeID,
   VersionID = (int)arrGroup.Max(mx=>mx.VersionID),
   Text = arrGroup.Text
};

But then, it returns all four of my array elements. Therefore, no good. I don't get the MAX like I want.

Please help!

Thanks.

Use

Text = arrGroup.OrderByDescending(mx=>mx.VersionID).First().Text

full query:

var myArrayQuery = from arr in array
group arr by arr.TypeID into arrGroup
select new
{
   TypeID = arrGroup.Key,
   VersionID = (int)arrGroup.Max(mx=>mx.VersionID),
   Text = arrGroup.OrderByDescending(mx=>mx.VersionID).First().Text
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM