在C#中从数组中查找相关的id

时间:2015-10-15 22:05:59

标签: c# linq

我有一些宠物对象。如果任何宠物在Duplicate属性中,我想为RelatedTo属性分配相同的号码。我可以根据相同的Duplicate号码判断哪些宠物与之相关。

可以修改宠物对象。

class Pet
{
    public int id { get; set;}
    public string Name { get; set; }
    public int Age { get; set; }
    public bool Vaccinated { get; set; }
    public string RelatedTo {get; set; }
    public int DuplicateTo {get; set;}
}

Pet[] pets ={ 
        new Pet { id = 1 ,Name="Barly", Age=8, Vaccinated=true , RelatedTo = "7,5"},
        new Pet { id = 3, Name="Robi", Age=3, Vaccinated=false, RelatedTo= "2" } ,
        new Pet { id = 2, Name="Toni", Age=1, Vaccinated=false, RelatedTo= "3" },
        new Pet { id = 7, Name="why", Age=4, Vaccinated=false, RelatedTo= "5,1" },
        new Pet { id = 5, Name="what", Age=1, Vaccinated=false, RelatedTo= "7,1" } 
        };

使用DuplicateTo

Pet[] pets ={ 
        new Pet { id = 1 ,Name="Barly", Age=8, Vaccinated=true , RelatedTo = "7,5" , DuplicateTo = 1},
        new Pet { id = 3, Name="Robi", Age=3, Vaccinated=false, RelatedTo= "2" , DuplicateTo = 2} ,
        new Pet { id = 2, Name="Toni", Age=1, Vaccinated=false, RelatedTo= "3" , DuplicateTo = 2},
        new Pet { id = 7, Name="why", Age=4, Vaccinated=false, RelatedTo= "5,1" , DuplicateTo = 1},
        new Pet { id = 5, Name="what", Age=1, Vaccinated=false, RelatedTo= "7,1" , DuplicateTo = 1} 
        };

1 个答案:

答案 0 :(得分:1)

如果你想为宠物和相关的数字设置相同的数字,这个C#代码将起作用。

private Pet[] SetDuplicateTo(Pet[] pets)
{
    int currentDupNumber = 1;
    foreach (var pet1 in pets)
    {
        if (pet1.DuplicateTo > 0) { continue; }
        var relatedPets = (from p in pets where pet1.RelatedTo.Split(',').Select(r => r.Trim()).Contains(p.id.ToString()) select p).ToList();
        if (relatedPets.Count > 0)
        {
            pet1.DuplicateTo = currentDupNumber;
            foreach (var pet2 in relatedPets)
            {
                pet2.DuplicateTo = currentDupNumber;
            }
        }
        currentDupNumber++;
    }
    return pets;
}