Поиск в элементах коллекции List - C#
Формулировка задачи:
Как можно реализовать метод для подсчета определенных параметров, которые хранятся внутри элементов такой вот коллекции:
Проблема в том что я могу оперировать элементами, но не пойму как получить доступ "внутрь" элементов коллекции coll
Листинг программы
- List<LiveBeings> coll = new List<LiveBeings>();
- Horse h = new Horse();
- Dog d = new Dog();
- Crucian c = new Crucian();
- FishSmallfry f = new FishSmallfry();
- coll.Add(h);
- coll.Add(d);
- coll.Add(c);
- coll.Add(f);
Решение задачи: «Поиск в элементах коллекции List»
textual
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- public class Program
- {
- public static void Main(string[] args)
- {
- var coll = new List<LiveBeings>();
- coll.Add(new Dog());
- coll.Add(new Dog());
- coll.Add(new Horse());
- coll.Add(new FishSmallfry());
- var list = coll.GetObjectsWithField("Legs");
- foreach (var e in list)
- {
- Console.WriteLine(e.GetType().Name);
- }
- Console.WriteLine(list.Sum());
- }
- }
- internal static class FilterList
- {
- public static int Sum(this IEnumerable<LiveBeings> source)
- {
- if (source == null)
- throw new ArgumentNullException("source");
- var num = 0;
- foreach (var leg in source.ToList().GetObjectsWithField("Legs"))
- {
- checked
- {
- num += ((dynamic) leg).Legs;
- }
- }
- return num;
- }
- public static IEnumerable<T> GetObjectsWithField<T>(this List<T> list, string fieldName)
- {
- return list.Where(e => HasField(e, fieldName));
- }
- private static bool HasField<T>(T element, string fieldName)
- {
- var t = element.GetType();
- return t.GetFields(BindingFlags.Public | BindingFlags.Instance).Any(f => f.Name == fieldName);
- }
- }
- internal class FishSmallfry : LiveBeings
- {
- }
- internal class Crucian : LiveBeings
- {
- }
- internal class Dog : LiveBeings
- {
- public int Legs = 4;
- }
- internal class Horse : LiveBeings
- {
- public int Legs = 4;
- }
- internal class LiveBeings
- {
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д