C# 使用 LINQ 判断集合中对象属性是否相同
在 C# 中,你可以使用 'LINQ' 查询来判断集合中某个对象的属性是否都相同。下面是一个示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
List<Person> people = new List<Person>()
{
new Person { Name = 'John', Age = 25 },
new Person { Name = 'Jane', Age = 30 },
new Person { Name = 'John', Age = 25 }
};
bool allNamesAreSame = people.Select(p => p.Name).Distinct().Count() == 1;
bool allAgesAreSame = people.Select(p => p.Age).Distinct().Count() == 1;
Console.WriteLine($'All names are same: {allNamesAreSame}');
Console.WriteLine($'All ages are same: {allAgesAreSame}');
}
}
在上述示例中,我们创建了一个 'Person' 类,并使用 'List
首先,我们通过 'Select' 方法选择所有 'Name' 属性的值,并使用 'Distinct' 方法获取所有不重复的值。如果不重复的值的数量为 1,表示所有的 'Name' 属性都相同。
接着,我们使用同样的方法判断 'Age' 属性是否都相同。
最后,我们通过打印结果来输出判断的结果。
运行上述代码,将会得到以下输出:
All names are same: False
All ages are same: False
因为 'people' 集合中的 'Name' 和 'Age' 属性并不都相同,所以输出结果为 'False'。
原文地址: https://www.cveoy.top/t/topic/peh0 著作权归作者所有。请勿转载和采集!