logo
down
shadow

Group by with different select in linq


Group by with different select in linq

By : Daniel Gallacher
Date : November 21 2020, 09:01 AM
should help you out Three suggestions.
Firstly, you can use SelectMany to map each group to a sequence of items and have the sequences merged back together for you, rather than using Select and having it add to a list as a side-effect.
code :
return source
    .GroupBy(vm => new { vm.AccountName, vm.Ref1, vm.Ref2})
    .SelectMany(group =>
        {
            if (string.IsNullOrWhiteSpace(group.Key.Ref1) ||
                string.IsNullOrWhiteSpace(group.Key.Ref2))
            {
                // keep the group separate
                return (IEnumerable<AccountViewModel>)group;
            }
            else
            {
                // just use one item
                return new[] { group.First() };
            }
        });


Share : facebook icon twitter icon
Linq Group By - select a single record in each group into typed result

Linq Group By - select a single record in each group into typed result


By : Boran
Date : March 29 2020, 07:55 AM
With these it helps The below is query is similar to what I am trying to achieve but simplified. In my actual code, I have four table joins and trying to get a result which has latest version in it. I have C# version I got very close to, but could not create a Vb version with type result set , I guess this will solve your issue
code :
var query =
from customeraddress in db.CustomerAddresses
join customers in db.Customers on new { CustId = customeraddress.CustId } equals new { CustId = customers.Id }
join LatestVersion in
    (
        (from customeraddress_1 in db.CustomerAddresses
            group customeraddress_1 by new
            {
                customeraddress_1.CustId
            } into g
            select new
            {
                CustId = (System.Int32)g.Key.CustId,
                MaxVersion = (System.Int32)g.Max(p => p.Version)
            }))
        on new { customeraddress.CustId, customeraddress.Version }
    equals new { CustId = Convert.ToInt32(LatestVersion.CustId), Version = Convert.ToInt32(LatestVersion.MaxVersion) }
select new
{
    Id = (System.Int32)customers.Id,
    customers.Field1,
    customers.Field2,
    customeraddress.Field3,
    customeraddress.Field4,
    Version = (System.Int32)customeraddress.Version
};
var results = query.ToList();
When using Linq's GROUP BY to create a list of groups, how can I select a specific group by its key?

When using Linq's GROUP BY to create a list of groups, how can I select a specific group by its key?


By : user2674646
Date : March 29 2020, 07:55 AM
seems to work fine You have to explicitly define your projection (ie. "pack" your group). Some useful LINQ code samples are available here.
see below for a working C# version of your code:
code :
var books = new[] { new Book("A book"),
    new Book("Your Book"),
    new Book("My book"),
    new Book("Anne's book") };

var titleGroups = from book in books
    orderby book.FirstLetter
    group book by book.FirstLetter
    into bookGroup select new {FirstLetter = bookGroup.Key, Books = bookGroup};

var currentGroup = from Grp in titleGroups 
     where Grp.FirstLetter == "A"
     select Grp.Books;

foreach (var group in currentGroup)
{
    Console.WriteLine(group.Key);  // First letter

    foreach (var book in group)
    {
        Console.WriteLine(book.Title);
    }
}
Group items and select specific item from each group with LINQ

Group items and select specific item from each group with LINQ


By : user2739442
Date : March 29 2020, 07:55 AM
I wish did fix the issue. There has got to be a one-liner to do this, and I just can't find it. , I think you want:
code :
var q = from x in new XPQuery<XPContent>(s)
        group x by x.ContentID into g
        let latest = g.OrderByDescending(a => a.Date).First()
        select new 
        {
            latest.Category, latest.ContentType,
            latest.Name, latest.ContentID, latest.Date
        };
LINQ Group By if an object has x number of properties, then select on each group

LINQ Group By if an object has x number of properties, then select on each group


By : singuibeogo w narcis
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I think the key is the SelectMany not GroupBy -- This will "flatten" a sub-lists. As I've shown below:
With
code :
class Person{
  Collection<Communications> comm {get; set;}
}

class Communication{
  Collection<PersonSender> person {get; set;}
  Collection<BuildingSender> building {get; set;}
}

class PersonSender{
  string name {get; set; }
  Collection<Posts> posts {get; set;}
}

class BuildingSender{
  string name {get; set; }
  Collection<Posts> posts {get; set;}
}
var result =
   m.comm.SelectMany(x => x.person).Where(x => x.posts.Any()).Select(new () { x.name, x.posts})
 .Union(m.comm.SelectMany(x=> x.building).Where(x => x.posts.Any()).Select(new () {x.name, x.posts}));
LINQ group by and select random element from each group

LINQ group by and select random element from each group


By : Nahian
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I have a set of questions, where each question has a "Group" property. , That's simple.Just define your random instance outside of your query:
code :
Random rnd = new Random();
_questions = _questions.GroupBy( q => q.Group )
             .Select( g => g.ElementAt(rnd.Next(0, g.Count())) ).ToList();
Related Posts Related Posts :
  • How to get all ip address in LAN?
  • send value to controller using html.actionlink
  • Assembly "Microsoft.GeneratedCode" loaded
  • count the number of items in view in asp.net mvc
  • Shortcut Keys for Saving or Editing Record in C#
  • Very tricky/complex text formatting: How can I output a string[][] as a table?
  • Fill multiple textboxes after selecting a data from DropDownList in ASP.NET
  • How to launch an application after another is logged in in C#?
  • Unable to retrieve column values from one of the tables joined in a stored procedure?
  • Directories last file name display only
  • Why do I get a COMException when I try to initialize an Interop.Word.Application?
  • Finding subtotal for column in repeater control
  • dropdownlist item selected throw exception (stack empty)
  • How can I list IIS working processes programmatically?
  • How to access nested object from JSON with Json.NET in C#
  • OpenXml DataValidation set predefined List for columns
  • How to find recurring word groups in text with C#?
  • layout conrols to developp universal apps in windows 8.1 pro
  • Adding strings to a list via for loop xna
  • Using Vertex Arrays with OpenTK
  • Optimizing List<string>
  • C# Local variables
  • How can I merge the results of a group by Linq-to-XML query?
  • How to add Report in ASP.NET Project
  • C# How to display all instances of a loop in a label?
  • C# subscribe a function to System.Action that is subscribed to another System.Action: why does order matter?
  • Is there any negative effect to setting SqlCommand's CommandTimeout to a high value?
  • C# - TreeView Context Menu Out of Place when using keyboard
  • How to read stored procedure output and return it as list
  • How do you maintain changes made by VisualState triggers after setting another VisualState?
  • Should I be unit testing my bootstrapper and if so how?
  • using .SingleOrDefault() inside .Where() will raise the following exception:- System.NotSupportedException was unhandled
  • C# How would I fill a Form1 Parameter in the same seperate class
  • Access gridview row's data from LinkButton inside that row
  • Translating excel function to c# Math.pow not resulting in same values
  • Arranging Ten Inputted Numbers into Ascending and Descending order
  • AsEnumerable and Query Syntax
  • How can I defensively code against randomly referencing "Table 0" and null values?
  • Changing xaml code position based on screen size
  • Castle Windsor resolve ienumerable and name
  • Drawing multiple sprites with a for loop xna 4.0
  • For loop to Populate Textblocks
  • Visual Studio 2015: Create an Empty Project
  • What are .NET classes to replace the old MSXML2.ServerXMLHTTP?
  • Handle leak in .Net threads
  • Excel add-in ribbon click events bubbling
  • validation rule needed for only numbers to be entered
  • Parsing complex XML, no descendent elements exists when selecting a named element
  • Web Api - IEnumerable with complex type as param is null
  • Email address input validation
  • .Net AND operator Regular Expression using strings in a document
  • Windows phone 8.1 POST x-www-form-urlencoded not working
  • Is there any way to make my C# XMLManager work?
  • ASP.NET 5 Console Application (package) - How to create DBContext from connection string?
  • How to use form's function in other class C#
  • WPF Zebra EPL2 Printing issue
  • C# use reflection to capture exception throw
  • Convert strings in DataRow to double
  • Xml-Serialization is not working
  • HTML Agility Pack can't find classes with trailing spaces
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co