【问题标题】:Convert Javascript Reduce Function to C#将 Javascript Reduce 函数转换为 C#
【发布时间】:2020-06-23 12:41:21
【问题描述】:

我正在尝试将此函数从 Javascript 转换为 C#。 目标是接收合同列表并将它们分类为子组,如果它们具有相同的客户,则将它们捆绑在一起。

> let c1 = {id:1,name:"c1"} 
> let c2 = {id:2,name:"c2"} 
> let c3 =  {id:2,name:"c3"} 
> let c4 = {id:1,name:"c4"} 
> let c5 = {id:3,name:"c5"}
> let list = [c1,c2,c3,c4,c5]
> 
> const groupByKey = (array, property) => {   return
> array.reduce((accumulator, object) => {
>     const key = object[property];
> 
>     if (!accumulator[key]) {
>       accumulator[key] = []
>     }
>     accumulator[key].push(object)
>     return accumulator;   }, {}) }
> 
> groupByKey(list, "id") 
> 
> // input = let list = [c1,c2,c3,c4,c5] //output =
> {"1":[{"id":1,"name":"c1"},{"id":1,"name":"c4"}],"2":[{"id":2,"name":"c2"},{"id":2,"name":"c3"}],"3":[{"id":3,"name":"c5"}]}

// 最好是输出包含捆绑合约的列表列表。

更新: 我已经编写了函数,问题是我只需要返回合同 ID,而不是整个对象。

desired output [[c1.id,c4.id],[c2.id,c3.id],[c5.id]]

这是我目前拥有的。

        public JsonResult checkForSameClient(long[] listOfContracts)
        {
// here i grab the list of contracts ids then go to my repository and find //the whole objects to be compared.






IQueryable<ContratEspace> contrats = contratEspaceRepository.Get(1, listOfContracts.Count(), listOfContracts);
                var contratList = contrats.ToList();

            var finalArray = contrats.GroupBy(c => c.id_clientGestion).ToList();
            return new JsonResult() { Data = finalArray };
        }

但这并没有正确返回 Json.Data 我有错误:

SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at fromJson (angular.js:1282)
    at defaultHttpResponseTransform (angular.js:10133)
    at angular.js:10224
    at forEach (angular.js:321)
    at transformData (angular.js:10223)
    at transformResponse (angular.js:10996)
    at processQueue (angular.js:15552)
    at angular.js:15568
    at Scope.$eval (angular.js:16820)

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 与 javascript array.reduce(...) 对应的 .NET 是 Enumerable.Aggregate(...) docs.microsoft.com/en-us/dotnet/api/…
  • ive 尝试转换为 .Aggregate 但无法使其以相同的方式工作。此外,尝试使用 GroupBy() 来尝试简化。我用香草语法写了一个嵌套循环,但它没有给我想要的输出。
  • 新语法错误SyntaxError: Unexpected token &lt; in JSON at position 0 不应与GroupBy(...) 相关。出于某种原因,您对后端控制器的调用不会返回 json。可能是控制器因某些异常而崩溃,并返回了一些通用错误页面。如果可能,尝试从 Chrome 或其他网络浏览器调用后端控制器方法。

标签: javascript c# arrays entity-framework jsonresult


【解决方案1】:

由于 GroupBy 是在 .NET 中构建的,因此无需编写聚合函数。

如何在 C# 中对列表进行分组:

var list = new [] {
   new { Id = 1, Name = "c1"},
   new { Id = 2, Name = "c2"},
   new { Id = 2, Name = "c3"},
   new { Id = 1, Name = "c4"},
   new { Id = 3, Name = "c5"},
};

var grouped = list.GroupBy(x => x.Id);

lambda 函数 x =&gt; x.Id 可以根据您的需要进行定制

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?view=netcore-3.1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-08
    • 2017-12-30
    • 1970-01-01
    • 2011-12-24
    • 2016-06-02
    • 2022-01-04
    • 2016-11-26
    相关资源
    最近更新 更多