-1
"Montgomery"を渡すときに "alamaba"を返すC#関数を書きたいと思います。ネストされたリスト - 親リストのリスト項目を取得する
第二例:シトカ - ここ>アラスカ
は、例のリストである:ここ
List<PopulationUSA> result = new List<PopulationUSA>();
PopulationUSA usa = new PopulationUSA("Population in USA", 316128839, new List<PopulationUSA>());
result.Add(usa);
PopulationUSA alabama = new PopulationUSA("Alabama", 4833722, new List<PopulationUSA>());
usa.Items.Add(alabama);
alabama.Items.Add(new PopulationUSA("Birmingham", 212113, null));
alabama.Items.Add(new PopulationUSA("Montgomery", 201332, null));
alabama.Items.Add(new PopulationUSA("Mobile", 194899, null));
PopulationUSA alaska = new PopulationUSA("Alaska", 735132, new List<PopulationUSA>());
usa.Items.Add(alaska);
alaska.Items.Add(new PopulationUSA("Juneau", 32660, null));
alaska.Items.Add(new PopulationUSA("Ketchikan", 8214, null));
alaska.Items.Add(new PopulationUSA("Sitka", 9020, null));
クラスです:
public class PopulationUSA
{
public PopulationUSA(string name, int value, List<PopulationUSA> items)
{
Name = name;
Value = value;
Items = items;
}
public string Name { get; set; }
public int Value { get; set; }
public List<PopulationUSA> Items { get; set; }
}
はどのように私はそれを行うことができますか? おかげ
あなたはあなたの例では、このようpublic string FindParentsOfGrandChildren(string _name)
{
List<PopulationUSA> parents = Items.Where(s => s.Items.Any(c => c.Name == _name)).ToList();
if (parents != null)
{
string listparents = string.Empty;
for (int i = 0; i < parents.Count; i++)
{
if (i == 0)
{
listparents += parents[i].Name;
}
else
{
listparents += ", " + parents[i].Name;
}
}
return listparents;
}
else
{
return "Not found";
}
}
その後、PopulationUSAクラスにこのメソッドを追加し、それを使用することができます
あなたが尋ねていることや問題がどこにあるかは本当に不明です。さらに、これまでに試したことの例を示すとよいでしょう –
何を試しましたか?あなたはこれにlinqを使う方法を知っていますか? –
最初の州はその名前の都市になります。 'result.FirstOrDefault(s => s.Items.Any(c => c.Name ==" Birmingham "))?名前? "Unknown" 'その名前の都市を持つすべての州が必要な場合は、' Where'に切り替えます。 – juharr