如何在C#中将此数据字符串分配给Tuple?

时间:2019-03-05 17:23:31

标签: c# tuples

我想知道如何将以下返回值((来自圆检测功能的图像名称,[X_cord,Ycord,半径])分配给我定义的数据结构。 我的返回数据流如下:(方括号用“ \ r \ n”分隔。

"C:\stars\d7_fr_bfdf_c0_non_201218_200822_hm_0_d.jpg , [[[278 734  33]
  [396 380  33]
  [396 616  32]
  [748 734  33]
  [750 262  33]
  [630 616  33]
  [160 144  32]
  [514 260  34]
  [ 44 498  33]
  [514 498  33]
  [280 262  33]
  [512 734  32]
  [632 144  33]
  [280 498  32]
  [630 380  33]
  [ 44  26  33]
  [ 44 260  34]
  [398 140  36]
  [752 500  34]
  [514  26  33]
  [160 380  32]
  [158 616  36]
  [ 42 736  33]
  [750  24  34]
  [276  26  32]]]"

我想分配返回值以遵循数据结构:

public class CircleCordinates
{   // Do not change the order
    [DataMember]
    public string image { get; set; }
    [DataMember]
    public List<Tuple<double, double, double>> circle { get; set; }
} 

最好的方法是什么?

关于, Pubudu

1 个答案:

答案 0 :(得分:1)

我将您的字符串放入const字符串中:

private const string StringToParse = 
@"C:\stars\d7_fr_bfdf_c0_non_201218_200822_hm_0_d.jpg , [[[278 734  33]
  [396 380  33]
  [396 616  32]
  [748 734  33]
  [750 262  33]
  [630 616  33]
  [160 144  32]
  [514 260  34]
  [ 44 498  33]
  [514 498  33]
  [280 262  33]
  [512 734  32]
  [632 144  33]
  [280 498  32]
  [630 380  33]
  [ 44  26  33]
  [ 44 260  34]
  [398 140  36]
  [752 500  34]
  [514  26  33]
  [160 380  32]
  [158 616  36]
  [ 42 736  33]
  [750  24  34]
  [276  26  32]]]";

并编写了此函数:

 private const string MyPattern = @"\[\s*(?<x>\d{1,3})\s+(?<y>\d{1,3})\s+(?<r>\d{1,3})\]";
 private static readonly Regex MyRegex = new Regex(MyPattern);
 public static CircleCordinates ParseIt()
 {
     var firstSplit = StringToParse.Split(',');
     var path = firstSplit[0].Trim();
     var data = firstSplit[1];

     var matches = MyRegex.Matches(data);
     var circle = new List<Tuple<double, double, double>>();
     foreach (var match in matches.Cast<Match>())
     {
         var tuple = new Tuple<double, double, double>(
             double.Parse(match.Groups["x"].ToString()),
             double.Parse(match.Groups["y"].ToString()),
             double.Parse(match.Groups["r"].ToString()));
         circle.Add(tuple);
     }

     var result = new CircleCordinates {image = path, circle = circle};
     return result;
 }

似乎可行。