在LINQ json结果中对多个表进行分组

时间:2019-01-27 12:52:07

标签: c# linq

如何显示10个类别如下的食谱:

   {"CategoryName":"CategoryName1",

   .
   .
   .
   10 recipe item
   },
   {"CategoryName":"CategoryName2",

   10 recipe item
   }

我的代码:

 ---------------------------------------------------------------

     var infoQuery = (from r in db.tbRecipe
                             join s in db.tbCategory
                                 on r.CategoryID equals s.ID
                             group new { r, s } by new { r.ID,r.CaloryValue,r.CategoryID,r.CoockTime,r.ImageList,r.Name,r.VideoURL , s.CategoryName } 
                             into grp 
                             select new
                             {
                                 grp.Key.CategoryName,
                                 grp.Key.ID,
                                 grp.Key.ImageList,
                                 grp.Key.Name,
                                 grp.Key.CaloryValue,
                                 grp.Key.CoockTime,
                             }).Take(10);


            return Json(infoQuery.ToList());

    -----------------------------------------------------------
      my result:        

    [
{
    "CategoryName": "ایرانی",
    "ID": 1,
    "ImageList": null,
    "Name": "باقالی پلو",
    "CaloryValue": "200",
    "CoockTime": 20
},
{
    "CategoryName": "فوت وفن",
    "ID": 2,
    "ImageList": null,
    "Name": "میگو",
    "CaloryValue": "100",
    "CoockTime": 10
},
{
    "CategoryName": "بین المللی",
    "ID": 3,
    "ImageList": null,
    "Name": "باقالی پلو",
    "CaloryValue": "200",
    "CoockTime": 20
},
{
    "CategoryName": "بین المللی",
    "ID": 4,
    "ImageList": null,
    "Name": "میگو",
    "CaloryValue": "100",
    "CoockTime": 10
},
{
    "CategoryName": "دریایی",
    "ID": 5,
    "ImageList": null,
    "Name": "باقالی پلو",
    "CaloryValue": "200",
    "CoockTime": 20
},
{
    "CategoryName": "دریایی",
    "ID": 6,
    "ImageList": null,
    "Name": "میگو",
    "CaloryValue": "100",
    "CoockTime": 10
}
 ]

2 个答案:

答案 0 :(得分:0)

我改进了您的查询,这应该可以解决问题。

    function testMe() {

    var ID = ''; // ID of your Document
    var name = ''; // Name of your sheet
    var sourceSheet = SpreadsheetApp.openById(ID); // Selects your Source Spreadsheet by its id
    var ssheet = sourceSheet.getSheetByName(name); // Selects your Source Sheet by its name

    var scoreRange = ssheet.getRange(2, 3, (sourceSheet.getLastRow() -1), (sourceSheet.getLastColumn() -2)); // Selects the range in which you will enter your scores
    var dateRange = ssheet.getRange(2,2,(sourceSheet.getLastRow() -1)); // Selects the range for which player names in row 1
    var playerRange = ssheet.getRange(1,3,1,(sourceSheet.getLastColumn() -2)); // selects the range for which dates were entered in column
    var topScorerRange = ssheet.getRange(2,1,scoreRange.getNumColumns()); // selects the range where your topscorer output will end up

    var numberOfPlayers = playerRange.getNumColumns(); // Gets the number of players you've already entered in row 1
    var numberOfGames = playerRange.getNumRows(); // Gets the number of games whose dates you've already entered in Column B


    function sortAndUpdateTopScorers() {
        var array = scoreRange.getValues();
        var totalPlayers = scoreRange.getNumColumns();
        var totalGames = scoreRange.getNumRows();
        var playerScores = [];

      // iterate through the scoreRange and count up each players total score

           for (var i = 0; i < totalPlayers; i++) {
               var currentPlayer = 0;
               for (var j = 0; j < totalGames; j++) {
                  currentPlayer += array[j][i];
               }
             playerScores.push([currentPlayer]);
           }

      // Combine the names of the players and their total score in order to create the strings for your topscorers column

      for (var v = 0; v < numberOfPlayers; v++) {
        playerScores[v].push(playerRange.getValues()[0][v] + ": " + playerScores[v]);
      };

      // Sort those strings according to their score

      playerScores.sort(function(a,b) {
      return b[0]-a[0]
      });

      // Remove the score value so only the string remains in the array

      for (var x = 0; x < playerScores.length; x++) {
       playerScores[x].shift(); 
      }

      // Write the content of the array into your topscorers column

      topScorerRange.setValues(playerScores);

     };
sortAndUpdateTopScorers();
};

答案 1 :(得分:0)

您可以得到如下结果:

var lstCategory = new List<Category> { new Category { Id=1}, new Category {Id=2 }, new Category { Id = 3 } };

var lstRecipe = new List<Recipe> { new Recipe { Id=1,Name="C1",CatId=1}, new Recipe { Id = 2, Name = "C2", CatId = 2 },
        new Recipe { Id =3, Name = "C3", CatId = 2 },new Recipe { Id =3, Name = "C4", CatId = 3 },new Recipe { Id=1,Name="C5",CatId=1} };

var result = (from c in lstRecipe
                 join s in lstCategory
                 on c.CatId equals s.Id
                 group c by c.CatId
                 into g
                 let o = g.Take(10)
                 select o);

var lstItems = new List<DtoModel>();

    foreach(var r in result)
    {
        var item = new DtoModel { Recipet = new List<RecipetDto>() };
        item.CategoryName = r.First().CatId.ToString();
        foreach(var s in r)
        {
            item.Recipet.Add(new RecipetDto
            {
                Id=s.Id,
                Name=s.Name
            });
        }
        lstItems.Add(item);
    }

,然后按以下方式获取json数据:

string jsonResult = JsonConvert.SerializeObject(lstItems, Formatting.Indented,
   new JsonSerializerSettings
   {
       ReferenceLoopHandling = ReferenceLoopHandling.Ignore
   });

您的dto类:

class DtoModel
{
public string CategoryName { get; set; }
public List<RecipetDto> Recipet { get; set; }}
相关问题