Select all columns but group by only one in linq,How to Get only Id from Lookup field in LINQ

Mohammad Qasim 576 Reputation points
2020-09-14T18:56:46.207+00:00

Greetings

I am using Sharepoint 2016 on Prem

I want to Select all columns but apply "group by" only one using LINQ ( retrieve data from Sharepoint list )

Problem : Currently having 2 problems/challenges

Problem 1: I have lookup field which returns id with name like "23;#abcd" , for this I have to split to get Id only ( mention in below code using split(';').

Problem 2: in LINQ query ,I want to select stautus and documentname columns from list not on "group by".
Group by is just for 1 column like we do in sql server like below

select id,stautus ,documentname,comments from abc groupby userFk

My Code:
oQuery.Query = "<Where><Eq><FieldRef Name='Flag'/><Value Type ='number'>" + 1 + "</Value></Eq></Where> ";

var resultfoldeDoc11 = (from SPListItem itm in pLis.GetItems(oQuery)
orderby itm["ID"]
group itm by new { m_folderID22 = itm["DocumentFolderFk"] } into g
select new { m_folderId22 = g.Key.m_folderID22.ToString().Split(';'), m_totaldocsfoldercount = g.Count() });

Solution Required:for Both Problem
How can I select multiple columns in select clause with one field in "Groupby " Clause ?
How can I get only ID from Look up field in LINQ

Thanks

Microsoft 365 and Office SharePoint Server Development
0 comments No comments
{count} votes

Accepted answer
  1. ZhengyuGuo 10,586 Reputation points Moderator
    2020-09-15T03:11:03.24+00:00

    Hi @Mohammad Qasim ,

    Change code like this:

    oQuery.Query = "<Where><Eq><FieldRef Name='Flag'/><Value Type ='number'>" + 1 + "</Value></Eq></Where> ";  
      
      
    var resultfoldeDoc11 = (from SPListItem itm in pLis.GetItems(oQuery)  
    orderby itm["ID"]  
    group itm by new { m_folderID22 = itm["DocumentFolderFk"] } into g  
    select new { m_folderId22 = g.Key.m_folderID22.ToString().Split(new char[] { ';', '#' })[0], m_totaldocsfoldercount = g.Count(), ListItemsData = g });  
      
     foreach (var oitem in resultfoldeDoc11)  
     {  
              Console.WriteLine($"{oitem.m_folderId22}:{oitem.Total}");  
              foreach (var item in oitem.ListItemsData)  
              {  
                //OutPut Other Columns here  
    			Console.WriteLine(item["Title"]);  
              }  
     }  
    

    ListItemsData = g will output the ListItem Collection object, then you can get any other fields using item["ColumnInternalName"] like the code sample above.

    Reference:

    Group By SPListItem in SharePoint ListItemCollection


    If the Answer is helpful, please click "Accept Answer" and upvote it.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.