根据条件组合/合并3个对象列表

本文关键字:3个 对象 列表 合并 条件 组合 | 更新日期: 2023-09-27 17:49:30

public class Derp
{
    public Derp
    {
        listOfStrings = new List<string>();
    }
    public string strName;
    public List<string> listOfStrings;
    public int unrequiredInt;
    public bool unrequiredBool;
}
List<Derp> derp1 = ... //generate data assume strName is unique in list, but not across lists;
List<Derp> derp2 = ... //generate data;
List<Derp> derp3 = ... //generate data;
List<Derp> mergedDerp = new List<Derp>();

我需要将derp1, derp2和derp3与条件derp1[x]合并。strName == derp2[y]。strName == derp3[z].strName。合并后的列表应该有所有的derp,但是根据上面的条件将derp1、2,3合并为一个derp (unrequiredInt和unrequiredBool的内容无关紧要)。我知道这可以在LINQ中完成,但我很困惑。比如…

mergedDerp = derp1.Join(derp2, d1 => derp1, d2 => derp2, (d1,d2) => new { ... ;
//and the next derp would be (i assume)
mergedDerp = mergedDerp.Join(derp3, md => mergedDerp, ...;

但是我不明白。

结果应该包含一个唯一的Derp的strName列表,如果任何Derp被合并,listofstring应该全部添加到新的Derp中。

根据条件组合/合并3个对象列表

使用GroupBy而不是Join似乎更适合您的情况:

var mergedDerp = derp1.Union(derp2).Union(derp3).GroupBy(x => x.strName)
    .Select(x => new Derp
        {
            strName = x.Key,
            // I guess you want to merge the list of strings as well?
            listOfStrings = x.SelectMany(d => d.listOfStrings).ToList()
            // Leave unrequired fields as default or just use the first derp's value
            // unrequiredInt = x.First().unrequiredInt,
            // unrequiredBool = x.First().unrequiredBool,
        })
    .ToList();

听起来您想根据strName值确定相等性。如果是这样,只需在对象上实现EqualsGetHashCode方法:

public class Derp
{
    public Derp()
    {
        listOfStrings = new List<string>();
    }
    public string strName;
    public List<string> listOfStrings;
    public int unrequiredInt;
    public bool unrequiredBool;

    public override bool Equals(object obj)
    {
        return ((Derp) obj).strName.Equals(strName);
    }
    public override int GetHashCode()
    {
        return strName.GetHashCode();
    }
} 

当你把它们组合在一起时,你可以只使用UnionDistinct:

var derp1 = new List<Derp>();
derp1.Add(new Derp() {strName = "X"});
derp1.Add(new Derp() { strName = "Y" });
derp1.Add(new Derp() { strName = "Z" });
var derp2 = new List<Derp>();
derp2.Add(new Derp() {strName = "A"});
derp2.Add(new Derp() { strName = "B" });
derp2.Add(new Derp() { strName = "X" });

var derp3 = new List<Derp>();
derp3.Add(new Derp() { strName = "J" });
derp3.Add(new Derp() { strName = "B" });
derp3.Add(new Derp() { strName = "X" });

var merged = derp1.Union(derp2.Union(derp3)).Distinct();
Console.WriteLine(merged.Count());   // Returns 6: X, Y, Z, A, B, J