c#-linq-get-attribute-list-from-table
To get a list of attributes from a table using LINQ in C#, you can use the following code:
using System.Linq;
// Define your table class
public class MyTable
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
// Other attributes...
}
// Create a list of MyTable objects
List<MyTable> myTableList = new List<MyTable>();
// Add some data to the list
myTableList.Add(new MyTable { Id = 1, Name = "John", Age = 30, Gender = "Male" });
myTableList.Add(new MyTable { Id = 2, Name = "Jane", Age = 25, Gender = "Female" });
myTableList.Add(new MyTable { Id = 3, Name = "Bob", Age = 40, Gender = "Male" });
myTableList.Add(new MyTable { Id = 4, Name = "Alice", Age = 35, Gender = "Female" });
// Use LINQ to get a list of attributes
var attributesList = myTableList
.Select(t => new { t.Name, t.Age, t.Gender })
.ToList();
// Print the list of attributes
foreach(var attribute in attributesList)
{
Console.WriteLine($"Name: {attribute.Name}, Age: {attribute.Age}, Gender: {attribute.Gender}");
}
In this example, we first define a table class called MyTable with some attributes. We then create a list of MyTable objects and add some data to it.
To get a list of attributes, we use the LINQ Select method to select only the attributes we want (Name, Age, and Gender) and create a new anonymous object with those attributes. We then call ToList to convert the LINQ query to a list.
Finally, we loop through the list of attributes and print them to the console.
原文地址: https://www.cveoy.top/t/topic/ryA 著作权归作者所有。请勿转载和采集!