求助:使用C# LINQ解析特定格式的键值对字符串
Fixing Your LINQ Logic for Extracting Data from the Delimited String
Got it, let's work through this problem together. Your target string follows a repeating pattern of 448=[Name],447=[Value],452=[Code], and you need to map specific 452 codes (63, 11, 13) to properties in your PartyRoleModel. Let's fix your LINQ approach and resolve the issues you're facing.
Key Issues in Your Original Code
- Incorrect Initial Split: Using
Split("453=")doesn't align with your grouping based on448=, which breaks the logical chunks you need to process. - Lost Context After Split: Splitting on
448=removes the delimiter, so checking forStartsWith("448=")in your LINQ query will never match. - Fragile Matching: Using
EndsWith("452=63,")is unreliable—your last block has extra trailing content, and not all blocks end with a comma.
Step-by-Step Solution
First, let's define your PartyRoleModel (adjust if your actual model differs):
public class PartyRoleModel { public string CompanyId { get; set; } public string UserId { get; set; } public string CompanyName { get; set; } public string PhyFlag { get; set; } // For 452=54 as mentioned }
Now, here's the corrected LINQ-based code to extract and map the data:
string rptstr = "11=205129022,453=8,448=CompanyID,447=D,452=63,448=userid,447=D,452=11,448=CompanyName,447=D,452=13,448=W,447=D,452=54,77=O,555=2"; // 1. Split the string into blocks centered around each 448= entry var blocks = rptstr.Split(new[] { "448=" }, StringSplitOptions.RemoveEmptyEntries); // 2. Parse each block into a structured object with key values var parsedBlocks = blocks.Select(block => { // Split into valid key-value pairs (ignore any trailing invalid entries) var kvPairs = block.Split(',') .Where(kv => kv.Contains('=')) .ToDictionary(kv => kv.Split('=')[0], kv => kv.Split('=')[1]); return new { // Extract the name (first part of the block, e.g., "CompanyID") BlockName = block.Split(',')[0], // Get 447 value if it exists Value447 = kvPairs.TryGetValue("447", out var val447) ? val447 : null, // Get 452 code if it exists Code452 = kvPairs.TryGetValue("452", out var code452) ? code452 : null }; }).ToList(); // 3. Map parsed blocks to your PartyRoleModel var partyRole = new PartyRoleModel { CompanyId = parsedBlocks.FirstOrDefault(b => b.Code452 == "63")?.Value447, UserId = parsedBlocks.FirstOrDefault(b => b.Code452 == "11")?.Value447, CompanyName = parsedBlocks.FirstOrDefault(b => b.Code452 == "13")?.Value447, PhyFlag = parsedBlocks.FirstOrDefault(b => b.Code452 == "54")?.Value447 };
How This Works
- Split on
448=: This gives us clean chunks of data, each starting with the name from448=(e.g.,CompanyID,447=D,452=63). - Dictionary for Key-Value Pairs: Converting each block into a dictionary makes it safe and easy to fetch
447and452values, regardless of their order in the block. - Targeted Mapping: Using
FirstOrDefaultwithCode452matches lets us reliably pull the447value for each specific code you care about.
Result
Running this code will populate your PartyRoleModel with:
CompanyId = "D"UserId = "D"CompanyName = "D"PhyFlag = "D"
内容的提问来源于stack exchange,提问作者Moh Mah
相关产品推荐
相关产品推荐

