简体   繁体   English

使用匿名类型从 Web API 调用生成不同的结果

[英]Generating different results from Web API call using an Anonymous type

I am trying to figure out the best way to return scatterplot data from API call.我试图找出从 API 调用返回散点图数据的最佳方法。 This is a graph that plots scores for the selected employees.这是一个绘制所选员工分数的图表。

My requirement are that the caller can specify one of a number of scores for each axis, either a named result score, an attributeId score or a domainId score.我的要求是调用者可以为每个轴指定多个分数之一,命名结果分数、attributeId 分数或 domainId 分数。

So in total there would be 30 total possibilities for the returned results.因此,返回的结果总共有 30 种可能性。

在此处输入图片说明

API Call: API调用:

[HttpPost("{id}/scatterplot")]
public ActionResult Scatterplot([FromRoute] int id, [FromBody] ScatterplotAxis axis)
    

ScatterplotAxis .cs散点图轴 .cs

public class ScatterplotAxis
{
    public Axis XAxis { get; set; }
    public Axis YAxis { get; set; }
}

public class Axis
{
    public int? TeamId { get; set; }  // optional
    public string NamedScore { get; set; }
    public int? AttributeId { get; set; }
    public int? DomainId { get; set; }
}

So the idea is that you can call it with data such as:所以这个想法是你可以用数据来调用它,例如:

{
  "xAxis": {
    "teamId": 1362,
    "namedScore": "NamedScore2",
    "attributeId": null,
    "domainId": null
  },
  "yAxis": {
    "teamId": 1362,
    "namedScore": "",
    "attributeId": 35,
    "domainId": 0
  }
}

So in the above example I would want to return a result with the score for 'NamedResult2' on X axis and the score for the given attributeId on the Y axis.所以在上面的例子中,我想返回一个结果,其中 X 轴上的 'NamedResult2' 得分和 Y 轴上给定 attributeId 的得分。

My problem is that I am trying to get what has been selected from the posted json and shape the results:我的问题是我试图从已发布的 json 中获取已选择的内容并调整结果:

So far I have:到目前为止,我有:

 var employees = ... // omitted for brevity
 // get employees and filter by teamId if it is supplied...

 var xAxisSelection = FindAxisSelection(axis.XAxis);
 var yAxisSelection = FindAxisSelection(axis.YAxis);

 if (xAxisSelection == "NotFound" || yAxisSelection == "NotFound")
     return BadRequest("Axis Selection not Found");

        // e.g. would have to do something like this for all 30 combinations using if/else
        // if(xAxisSelection == "NamedScore2" && yAxisSelection == "Attribute")

        var results = employees.Select(e => new
        {
            Id = e.Id,
            FullName = e.FullName,
            TeamName = e.MemberTeams.FirstOrDefault() == null ? "" : e.MemberTeams.FirstOrDefault().Name,

            // how to do this for all combinations???
            XAxis = e.NamedScores.NamedResult2,  
            YAxis = e.AttributeResults.Where(a => a.AttributeId == axis.YAxis).Score
        }).ToArray();

        return Ok(results);
    }

    private string FindAxisSelection(Axis axis)
    {
        if (axis.AttributeId != null || axis.AttributeId > 0)
            return "Attribute";
        else if(axis.DomainId != null || axis.DomainId > 0)
            return "Domain";
        else if(axis.NamedScore == "NamedScore1")
            return "NamedScore1";
        else if (axis.NamedScore == "NamedScore2")
            return "NamedScore2";
        else if (axis.NamedScore == "NamedScore3")
            return "NamedScore3";
        else if (axis.NamedScore == "NamedScore4")
            return "NamedScore4";

        return "NotFound";
    }

So my question is regarding generating the results.所以我的问题是关于生成结果。 I do not really want to use a massive if else statement block for each of the 30 combinations.我真的不想为 30 种组合中的每一种都使用大量的 if else 语句块。 Are there any design patterns I should use to make this cleaner and more efficient.有没有我应该使用的设计模式来使这个更干净、更高效。

I think its best to use anonymous type so that I don't have to create concrete types for each of the 30 combinations?我认为最好使用匿名类型,这样我就不必为 30 种组合中的每一种都创建具体类型?

Rules design pattern is a perfect fit for this use case.规则设计模式非常适合这个用例。 Have a look at the following link.看看下面的链接。

http://www.michael-whelan.net/rules-design-pattern/ http://www.michael-whelan.net/rules-design-pattern/

In short, what you can do is create numbers of objects with their own requirements(if condition in your case) and if a condition is met within the object they will execute their code otherwise it will call the next object.简而言之,您可以做的是创建许多具有自己要求的对象(如果在您的情况下是条件),如果在对象中满足条件,他们将执行他们的代码,否则它将调用下一个对象。 This approach is also known as chain of responsibility这种方法也称为责任链

Requested sample to give you an idea on how to so something to avoid multiple if conditions:-请求的示例让您了解如何避免多个 if 条件:-

public class Program
{
    public static void Main()
    {
        new AllSteps().Process(1);
    }
    public interface IStep
    {
        void Process(int x);
    }
    public class StepOne:IStep
    {
        public void Process(int x)
        {
            // do something with x
        }
    }
    public class StepTwo:IStep
    {
        public void Process(int x)
        {
            // do something with x
        }
    }
    public class AllSteps:IStep
    {
        readonly List<IStep> steps= new List<IStep>();

        public AllSteps()
        {
            this.steps.Add(new StepOne());
            this.steps.Add(new StepTwo());

        }

        public void Process(int x)
        {
            steps.ForEach(y=>y.Process(x));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM