You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用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

  1. Incorrect Initial Split: Using Split("453=") doesn't align with your grouping based on 448=, which breaks the logical chunks you need to process.
  2. Lost Context After Split: Splitting on 448= removes the delimiter, so checking for StartsWith("448=") in your LINQ query will never match.
  3. 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 from 448= (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 447 and 452 values, regardless of their order in the block.
  • Targeted Mapping: Using FirstOrDefault with Code452 matches lets us reliably pull the 447 value 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:40:29