¡¡¥²¡¼¥àÆâ¤Ç¡¢ÆÃÄê¤Î¥¢¥¤¥Æ¥à¡ÊÎ㤨¤Ð¡¢²ÁÃͤ¬100°Ê¾å¤Î¥¢¥¤¥Æ¥à¡Ë¤ò»ý¤Ä¥¥ã¥é¥¯¥¿¡¼Ì¾¤ò¤¹¤Ù¤Æɽ¼¨¤·¤¿¤¤¤È¤·¤Þ¤¹¡£
¡¡°Ê²¼¤Î¤è¤¦¤Ê¥¯¥é¥¹¹½Â¤¤òÁÛÄꤷ¤Þ¤¹¡£
public class Item
{
public string Name { get; set; }
public int Value { get; set; }
}
public class Character
{
public string Name { get; set; }
public List<Item> Items { get; set; }
}
¡¡¤³¤³¤Ç¤Ï¡¢Character¤Î¥ê¥¹¥È¤«¤é¡¢Ì¾Á°¤¬ÆÃÄê¤Îʸ»úÎó¤Ë°ìÃפ¹¤ëºÇ½é¤ÎCharacter¤òõ¤¹½èÍý¤ò¹Í¤¨¤Þ¤¹¡£
¡¡¤Þ¤º¤Ï½é´ü²½¤ò¹Ô¤¤¡¢List ¤Î½àÈ÷¤òÀ°¤¨¤Þ¤¹¡£
// ¥¢¥¤¥Æ¥à¤ÎºîÀ®
Item sword = new Item { Name = "Sword", Value = 100 };
Item shield = new Item { Name = "Shield", Value = 150 };
Item potion = new Item { Name = "Potion", Value = 50 };
// ¥¥ã¥é¥¯¥¿¡¼¤ÎºîÀ®¤È¥¢¥¤¥Æ¥à¤Î³ä¤êÅö¤Æ
Character john = new Character
{
Name = "John",
Items = new List<Item> { sword, shield }
};
Character mary = new Character
{
Name = "Mary",
Items = new List<Item> { potion }
};
Character tom = new Character
{
Name = "Tom",
Items = new List<Item> { sword, potion }
};
// ¥¥ã¥é¥¯¥¿¡¼¤ò¥ê¥¹¥È¤Ë³ÊǼ
List<Character> characters = new List<Character> { john, mary, tom };
¡¡¤³¤Î¾ðÊó¤òÍøÍѤ·¤Þ¤¹¡£
¡¡¤Þ¤º¤ÏLINQ¤ò»È¤ï¤Ê¤¤½¾Íè¤ÎÊýË¡¤Ç¼ÂÁõ¤·¤Þ¤¹¡£
// ²ÁÃͤ¬100°Ê¾å¤Î¥¢¥¤¥Æ¥à¤ò»ý¤Ä¥¥ã¥é¥¯¥¿¡¼¤Î̾Á°¤ò³ÊǼ¤¹¤ë¥ê¥¹¥È
List<string> characterNames = new ();
foreach (Character character in characters)
{
foreach (Item item in character.Items)
{
if (item.Value >= 100)
{
characterNames.Add(character.Name);
break; // 1¤Ä¸«¤Ä¤«¤Ã¤¿¤é¼¡¤Î¥¥ã¥é¥¯¥¿¡¼¤Ø
}
}
}
// ̾Á°¤Î¥ê¥¹¥È¤òɽ¼¨
foreach (string name in characterNames)
{
Console.WriteLine(name);
}
¡¡¤³¤³¤Ç¤Ï¡¢foreach¤òÆó½Å¤Ë»È¤Ã¤Æ³Æ¥¥ã¥é¥¯¥¿¡¼¤Î³Æ¥¢¥¤¥Æ¥à¤òÄ´¤Ù¡¢¤½¤Î²ÁÃͤ¬100°Ê¾å¤Î¥¢¥¤¥Æ¥à¤ò»ý¤Ä¥¥ã¥é¥¯¥¿¡¼¤Î̾Á°¤ò¥ê¥¹¥È¤ËÄɲ䷤Ƥ¤¤Þ¤¹¡£
¡¡¤½¤ì¤ËÂФ·¤Æ¡¢LINQ¤ò»È¤¦¤È¡¢¤³¤Î½èÍý¤ÏÂçÉý¤Ë¥·¥ó¥×¥ë¤Ë¤Ê¤ê¤Þ¤¹¡£
var characterNames = characters
.Where(character => character.Items.Where(item => item.Value >= 100).ToList().Count > 0)
.Select(character => character.Name);
// ̾Á°¤Î¥ê¥¹¥È¤òɽ¼¨
foreach (string name in characterNames)
{
Console.WriteLine(name);
}
¡¡¤³¤³¤Ç¤Ï¡¢¤Þ¤ºWhere¥á¥½¥Ã¥É¤Ç³Æ¥¥ã¥é¥¯¥¿¡¼¤¬»ý¤Ä¥¢¥¤¥Æ¥à¤ÎÃ椫¤é²ÁÃͤ¬100°Ê¾å¤Î¥¢¥¤¥Æ¥à¤òÃê½Ð¤·¤Þ¤¹¡£
¤½¤·¤Æ¡¢¤½¤ì¤é¤Î¥¢¥¤¥Æ¥à¤Î¿ô¤¬0¤è¤êÂ礤¤¡Ê¤Ä¤Þ¤ê¡¢¾¯¤Ê¤¯¤È¤â1¤Ä¤Ï¸ºß¤¹¤ë¡Ë¥¥ã¥é¥¯¥¿¡¼¤òÃê½Ð¤·¤Þ¤¹¡£
¡¡¤½¤Î¸å¡¢Select¥á¥½¥Ã¥É¤Ç¤½¤Î¥¥ã¥é¥¯¥¿¡¼¤Î̾Á°¤ò¼èÆÀ¤·¤Æ¤¤¤Þ¤¹¡£
¡¡¼¡¤Ë³Ø½¬¤¹¤ë Any ¥á¥½¥Ã¥É¤òÍøÍѤ¹¤ë¤È¡¢¤µ¤é¤Ë¥·¥ó¥×¥ë¤Ë¤Ê¤ê¤Þ¤¹¡£
var characterNames = characters
.Where(character => character.Items.Any(item => item.Value >= 100))
.Select(character => character.Name);
// ̾Á°¤Î¥ê¥¹¥È¤òɽ¼¨
foreach (string name in characterNames)
{
Console.WriteLine(name);
}
¡¡character.Items.Any(item => item.Value >= 100) ¤Ï¡¢¥¥ã¥é¥¯¥¿¡¼¤¬ÊÝ»ý¤¹¤ë¥¢¥¤¥Æ¥à¤ÎÃæ¤Ë²ÁÃͤ¬100°Ê¾å¤Î¤â¤Î¤¬1¤Ä¤Ç¤â¤¢¤ë¤«¤É¤¦¤«¤ò¥Á¥§¥Ã¥¯¤·¤Æ¤¤¤Þ¤¹¡£
¤³¤ì¤¬ true ¤Î¾ì¹ç¡¢¤½¤Î¥¥ã¥é¥¯¥¿¡¼¤Ï·ë²Ì¤Î¥ê¥¹¥È¤Ë´Þ¤Þ¤ì¤Þ¤¹¡£
¡¡¤³¤ÎÉôʬ¤¬¡¢Àè¤Û¤É¤È¤Ï°Û¤Ê¤ëÉôʬ¤Ç¤¹¡£