C#将列表作为逗号分隔的字符串存储在字符串类型变量中,该字符串类型变量具有列表中项目的出现次数

时间:2018-07-06 16:42:08

标签: c# asp.net .net linq generics

我有一个List<Book> booksList类型的列表Book

public class Book
{
public int ID {get; set;}
public string Name {get; set;}
public DateTime date {get; set;}

}

让我们说此清单中有8本书,名字如下, book1, book2, book1, book4,book2, book4, book3, book4。 如您所见,列表中有许多相同的书名,但ID不同。 我想将相似的书名与该书名出现次数的乘积存储在列表中的一个名为string BooksName的字符串变量中,以逗号分隔的字符串,因此当我检索BooksName时我将有一个逗号这样的字符串值

"2 X book1 , 2 X book2 , 1 X book3 , 3 X book4"

因为列表中我有book1的2个,book2的2个,book3的1个和book4的3个。

我尝试了使用linq,但没有成功

string BooksName = booksList.GroupBy(r =>r.Name).Select(s => s.Select(e =>e.Name).Count() + " X " + s.Name).ToString();

之后 我该怎么办?

预先感谢专业人员

2 个答案:

答案 0 :(得分:2)

您只需要订购GroupBy的结果,修改您要选择的书名进行显示,然后使用string.Join()

void Main()
{
    var booksList = new List<Book>();
    booksList.Add(new Book { Name = "book1" });
    booksList.Add(new Book { Name = "book2" });
    booksList.Add(new Book { Name = "book1" });
    booksList.Add(new Book { Name = "book4" });
    booksList.Add(new Book { Name = "book2" });
    booksList.Add(new Book { Name = "book4" });
    booksList.Add(new Book { Name = "book3" });
    booksList.Add(new Book { Name = "book4" });

    string BooksName = string.Join(", ", booksList
        .GroupBy(r =>r.Name)
        .OrderBy(r => r.First().Name)
        .Select(s => s.Count() + " X " + s.First().Name));

    Console.WriteLine(BooksName);
    // Output: 2 X book1, 2 X book2, 1 X book3, 3 X book4
}

public class Book
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime date { get; set; }
}

答案 1 :(得分:1)

您不能仅使用.ToString枚举,而需要使用string.Join

var booksList = "book1, book2, book1, book4,book2, book4, book3, book4".Split(',')
    .Select(x => new Book { Name = x.Trim() })
    .ToList();

var BooksName = string.Join(", ", booksList
    .GroupBy(x => x.Name)
    .OrderBy(g => g.Key)
    .Select(g => $"{g.Count()} X {g.Key}")
);