我有两个List<Name>
s:
public class Name
{
public string NameText {get;set;}
public Gender Gender { get; set; }
}
public class Gender
{
public decimal MaleFrequency { get; set; }
public decimal MaleCumulativeFrequency { get; set; }
public decimal FemaleCumulativeFrequency { get; set; }
public decimal FemaleFrequency { get; set; }
}
如果NameText
属性匹配,我想从女性FemaleFrequency
和FemaleCumulativeFrequency
列表中选择Name
和MaleFrequency
,来自男性MaleCumulativeFrequency
列表的Name
值,并创建一个Name
列表,其中填充了所有四个属性。
使用.Net 3.5在C#中最简单的方法是什么?
答案 0 :(得分:5)
您是否尝试在合并列表时对每个值求和?如果是这样,尝试这样的事情:
List<Name> list1 = new List<Name>();
List<Name> list2 = new List<Name>();
List<Name> result = list1.Union(list2).GroupBy(x => x.NameText).Select(x => new
Name
{
NameText = x.Key,
Gender = new Gender
{
FemaleCumulativeFrequency = x.Sum(y => y.Gender.FemaleCumulativeFrequency),
FemaleFrequency = x.Sum(y => y.Gender.FemaleFrequency),
MaleCumulativeFrequency = x.Sum(y => y.Gender.MaleCumulativeFrequency),
MaleFrequency = x.Sum(y => y.Gender.MaleFrequency)
}
}).ToList();
这是做什么的:
IEnumerable<Name>
。 List<Name>
。 编辑:或者,正如您在下面所说,您只想合并两个列表...执行此操作:
List<Name> allNames = femaleNames.Union(maleNames).ToList();
答案 1 :(得分:2)
这看起来很像人口普查名频率数据,对吧?性别对于你所拥有的课程来说有点用词不当,更像是“频率数据”。
实际上你想要一个字典,这样你就可以查找任何名字并获得它的四个值。您可以简单地选择男性并对其进行ToDictionary(...)然后迭代女性,如果名称存在于词典中,则替换其上的女性概率,如果它不存在,则创建一个新的词典条目
我自己对同一数据的处理方法是在数据库中创建一个附加了所有四个值的表。
以下是您的方案的一些代码......
Dictionary<string, Gender> result;
result = males.ToDictionary(x => x.NameText, x => x.Gender);
foreach (var female in females)
{
if (result.ContainsKey(female.NameText))
{
result[female.NameText].FemaleCumulativeFrequency = female.Gender.FemaleCumulativeFrequency;
result[female.NameText].FemaleFrequency = female.Gender.FemaleFrequency;
}
else
result.Add(female.NameText, female.Gender);
}
答案 2 :(得分:1)
我认为这可能是你想要的,虽然我不确定它是否像你期望的那样处理累积频率:
var mergedNameList = maleNames
.Concat(femaleNames)
.GroupBy(n => n.NameText)
.Select(nameGroup => new Name
{
NameText = nameGroup.Key,
Gender = new Gender
{
MaleFrequency = nameGroup.Sum(n => n.Gender.MaleFrequency),
MaleCumulativeFrequency = nameGroup.Sum(n => n.Gender.MaleCumulativeFrequency),
FemaleFrequency = nameGroup.Sum(n => n.Gender.FemaleFrequency),
FemaleCumulativeFrequency = nameGroup.Sum(n => n.Gender.FemaleCumulativeFrequency)
}
}.ToList();