我有一个表客户端,它具有以下列
id first_name last_name clientid
1 tom saver 1590
2 john saver 1590
3 help Desk 0
4 tom saver 0
5 hello world 1590
我想使用LINQ返回一个像这样的新列表
full_name assClientids
tom saver 1590, 0
john saver 0
help desk 0
hello world 1590
我无法使用LINQ中的全名进行分组
答案 0 :(得分:2)
我写了一个快速控制台应用程序来显示。请参阅下面的课程,这应该可以为您提供所需的东西。
public class DbViewModel
{
public long TotalClients { get; set; }
public long FilteredCLients { get; set; }
public List<Client> Clients{ get; set; }
public List<int> AssociatedClientIds { get; set; }
}
public class Client
{
public Client() {}
public ClientLink ClientLink { get; set; }
public const string LastNameDisplayName = "Last Name";
public const int LastNameMaxLength = 100;
public const string LastNameMaxLengthStr = "100";
//[MaxLength(LastNameMaxLength)]
public string LastName { get; set; }
public const string FirstNameDisplayName = "First Name";
public const int FirstNameMaxLength = 30;
public const string FirstNameMaxLengthStr = "30";
//[MaxLength(FirstNameMaxLength)]
public string FirstName { get; set; }
public const string MiddleNameDisplayName = "Middle Name";
public const int MiddleNameMaxLength = 30;
public const string MiddleNameMaxLengthStr = "30";
//[MaxLength(MiddleNameMaxLength)]
public string MiddleName { get; set; }
public const string SuffixDisplayName = "Suffix";
public const int NameSuffixMaxLength = 10;
public const string NameSuffixMaxLengthStr = "10";
//[MaxLength(NameSuffixMaxLength)]
public string NameSuffix { get; set; }
public string FullName
{
get
{
return NameFormatter.Format(LastName, FirstName, MiddleName, NameSuffix);
}
}
}
public class ClientLink
{
public long ClientId { get; set; }
private List<ClientAddress> address = new List<ClientAddress>();
public ClientLink()
{
}
}
class Program
{
static void Main(string[] args)
{
List<DbModel> dbModels = DbModel.GetModels();
List<DbViewModel> viewModels = dbModels.GroupBy(x => x.first_name.ToLower() + ' ' + x.last_name.ToLower()).Select(fullNameGrouping =>
new DbViewModel()
{
full_name = fullNameGrouping.Key,
clientIds = fullNameGrouping.Select(x => x.clientId).ToList()
}).ToList();
Console.ReadKey();
}
}
答案 1 :(得分:1)
假设这是您的Client
班
public class Client
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int ClientID { get; set; }
}
我们可以对串联的名字和姓氏进行GroupBy
。
var clients = new List<Client>
{
new Client() { ID = 1, FirstName = "Tom", LastName = "Saver", ClientID = 1590 },
new Client() { ID = 2, FirstName = "John", LastName = "Saver", ClientID = 1590 },
new Client() { ID = 3, FirstName = "Help", LastName = "Desk", ClientID = 0 },
new Client() { ID = 4, FirstName = "Tom", LastName = "Saver", ClientID = 0 },
new Client() { ID = 5, FirstName = "Hello", LastName = "World", ClientID = 1590 }
};
var groupByFullName = clients.GroupBy(x => string.Concat(x.FirstName, " ", x.LastName));
现在,您的groupByFullName
集合按全名分组。