在列表中相互减去两个属性

时间:2015-01-14 14:40:25

标签: c#

我希望得到两个整数之间的差异,在本例中为“Age” - 减去它们。

这是我的班级和我的清单。我想用一种方法,从Robin和Sara那里取出年龄并显示年龄差异。这可能是LINQ或..?

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

public class LinqQuery
{
    private readonly List<Person> _persons = new List<Person>
    {
        new Person {FirstName = "Robin", LastName = "Blixt", Age = 29},
        new Person {FirstName = "Sara", LastName = "Johansson", Age = 44}
    };

    public IEnumerable<Person> GetAll()
    {
        return _persons;
    }

    public void difference()
    {
        ?????
        Console.ReadKey();
    }
}

提前致谢。

3 个答案:

答案 0 :(得分:0)

如果FirstName是您的密钥而您拥有的项目数多于两个,则可以使用lambda表达式查找指定的索引。 请注意,我没有检查任何错误(空列表等)

 public void diff() 
    { 

                int indxRobin = lst.FindIndex((item) => { return item.FirstName == "Robin"});
                int indxSara =  lst.FindIndex((item) => { return item.FirstName == "Sara"});

                return lst[indxRobin].Age - lst[indxSara].Age;
    }

答案 1 :(得分:0)

使用交叉联接,您可以计算列表中所有排列的年龄差异。

当然,这非常粗糙并且提供了所有重复项,但是从那里删除查询中的重复项很容易。

public void Difference()
{
    var ageDifferences = from p1 in _persons
                         from p2 in _persons
                         select new
                         {
                             P1FullName = p1.FirstName + " " + p1.LastName,
                             P2FullName = p2.FirstName + " " + p2.LastName,
                             AgeDifference = Math.Abs(p1.Age - p2.Age)
                         };

    foreach (var item in ageDifferences)
    {
        Console.Out.WriteLine("{0} and {1} have {2} years of age difference.", item.P1FullName, item.P2FullName, item.AgeDifference);
    }

    Console.ReadKey();
}

答案 2 :(得分:-2)

谢谢,@ Tim Schmelter的建议:)

public void difference()
{
    int sara= _persons.FirstOrDefault(p=>p.FirstName=="Sara").Age;
    int robin=_persons.FirstOrDefault(p=>p.FirstName=="Robin").Age;
    int difference= Math.abs(sara-robin);

    Console.ReadKey(); 
}