我想在通用列表中找到成员的名字,我们可以帮助我解决这个问题吗? 我必须检查列表中的每个用户,如果其中一个值等于例如" 100"必须知道这个值的名称。 我知道如何使用参数值,但我无法获得属性。
此致
public List<Users> LiUsers = new List<Users>();
private void button1_Click(object sender, EventArgs e)
{
int r = 100;
foreach (var user in LiUsers)
{
//do some stuff
//here I want name of member which equals int r ... eg "Value1" or "Value2" ...
}
}
private void FillUsers(string name, int id, int val1, int val2, int val3, int val4, int val5)
{
LiUsers.Add(new Users { Name = name, Id = id, Value1 = val1, Value2 = val2, Value3 = val3, Value4 = val4, Value5 = val4 });
}
}
public class Users : IEnumerable
{
public string Name { get; set; }
public int Id { get; set; }
public int Value1 { get; set; }
public int Value2 { get; set; }
public int Value3 { get; set; }
public int Value4 { get; set; }
public int Value5 { get; set; }
public IEnumerator GetEnumerator()
{
yield return Name;
yield return Id;
yield return Value1;
yield return Value2;
yield return Value3;
yield return Value4;
yield return Value5;
}
}
答案 0 :(得分:2)
您可以使用Reflection获取属性的值,然后使用LINQ获取值为100的属性的名称:
var userType = typeof(User);
var properties = userType
.GetProperties()
.Where(x => x.Name.StartsWith("Value")).ToList();
foreach (var user in LiUsers)
{
var property = properties.FirstOrDefault(x => (int)x.GetValue(user) == 100);
if(property != null)
{
string name = property.Name;
}
}