gpt4 book ai didi

c# 和 LINQ,其中集合成员的属性名称是通过函数传递的

转载 作者:行者123 更新时间:2023-11-30 16:23:47 25 4
gpt4 key购买 nike

一如既往,帮助/评论想法总是受到赞赏,并为我的编程幼稚表示歉意。

我正在尝试创建一个广泛适用的函数,该函数可用于涉及 block 随机化的 future 研究。 patientDataCollection 的每个成员都有一个 bool 属性,名称类似于 interventionArm、givenDrugX 或类似名称。该函数旨在(伪)随机分配给研究的一个分支,具体取决于 block 大小——也就是说,如果 block 大小为 8,则将 4 个分配给治疗,4 个分配给对照(无治疗)。

到目前为止的代码:

 public static bool nextAllocation<T>(int blockSize, IEnumerable<T> patientDataCollection, string allocationPropertyName)
{
int remainingAllocations = blockSize - patientDataCollection.Count();
if (remainingAllocations <= 0) throw new Exception("All alocations within block accounted for");
var p = typeof(T).GetProperty(allocationPropertyName);

int remainingInterventions = blockSize/2 - patientDataCollection.Count(c => c.p);
double Pintervention = (double)remainingInterventions / (double)remainingAllocations;
double rdm = new Random().NextDouble();
return (rdm <= Pintervention);
}

这当然是有缺陷的逻辑,因为变量 p 与 linq 语句 patientDataCollection.Count(c => c.p) 中引用的 c.p 无关。显然这个语句只是统计所有具有真值的元素。

ASP 为 4.0。任何人都可以看到如何实现这一点

最佳答案

您可以将 Func<T, bool> 传递给您的方法将用于计数。

public static bool nextAllocation<T>(int blockSize, IEnumerable<T> patientDataCollection, Func<T,bool> predicate) 
{
int remainingAllocations = blockSize - patientDataCollection.Count();
if (remainingAllocations == 0) throw new Exception("All alocations within block accounted for");
int remainingInterventions = blockSize/2 - patientDataCollection.Count(predicate);
double Pintervention = remainingInterventions / remainingAllocations;
double rdm = new Random().NextDouble();
return (rdm <= Pintervention);
}

用法示例如下:

var result = nextAllocation(10, collection, c=>c.interventionArm);

关于c# 和 LINQ,其中集合成员的属性名称是通过函数传递的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11255206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com