如何合并重复string对应的int值为带int列表的对象集合
Hey there! To achieve what you want—grouping entries by the string value and combining their integers into a list—you can use LINQ's grouping capabilities paired with a clear data structure to hold the merged results. Here's how to do it step by step:
Step 1: Define a Class for Merged Entries (Recommended)
First, create a concrete class to represent your merged objects. This makes working with the data much easier later on, compared to using anonymous types:
public class MergedEntry { public string Pars { get; set; } public List<int> Ids { get; set; } = new List<int>(); // Initialize with empty list by default }
Step 2: Merge Existing Individual Entries
If you already have a collection of individual (string, int) entries (either in your result list or another source), you can group them and convert to merged entries using LINQ:
Example Source Data
Let's say you have a list of individual items (this could be extracted from your existing result list if needed):
// Example: Your existing individual entries (replace with your actual data source) var individualEntries = new List<(string Pars, int Id)> { ("xxx", 1), ("xxx", 2), ("yyy", 3), ("xxx", 4), ("zzz", 5) };
Group and Merge
Use GroupBy to cluster entries by the Pars string, then create MergedEntry objects for each group:
var mergedEntries = individualEntries .GroupBy(entry => entry.Pars) .Select(group => new MergedEntry { Pars = group.Key, Ids = group.Select(entry => entry.Id).ToList() }) .ToList(); // Assign to your result list (cast to object if you need to keep List<object>) List<object> result = mergedEntries.Cast<object>().ToList();
After this, result will contain:
{ Pars = "xxx", Ids = [1,2,4] }{ Pars = "yyy", Ids = [3] }{ Pars = "zzz", Ids = [5] }
Step 3: Incremental Addition (Adding Items One by One)
If you're adding items to result incrementally (instead of processing a full list at once), check for existing entries before adding:
// Suppose you're adding a new entry: string newPars = "xxx"; int newId = 6; // Check if the Pars already exists in result var existingEntry = result.OfType<MergedEntry>().FirstOrDefault(e => e.Pars == newPars); if (existingEntry != null) { // Add the new Id to the existing list existingEntry.Ids.Add(newId); } else { // Create a new MergedEntry and add it to result result.Add(new MergedEntry { Pars = newPars, Ids = new List<int> { newId } }); }
Notes
- Avoid Anonymous Types: While you could use anonymous objects for merging, using a concrete class like
MergedEntrymakes it easier to access properties later (you can't easily cast anonymous types back to their original structure). - Handling Existing
resultData: If yourresultlist already contains individual (string, int) objects, first extract them usingresult.OfType<YourIndividualClass>().ToList()(replaceYourIndividualClasswith the class you used for single entries) before grouping.
内容的提问来源于stack exchange,提问作者Leo Messi

