简体   繁体   中英

C# Store A List As a Comma Separated String In String Type Variable With Number Of Occurrence Of Items In The List

I have a list List<Book> booksList of type Book

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

}

lets say we have 8 books in this list with following Names, book1, book2, book1, book4,book2, book4, book3, book4 . As you see so many same book name with different ID is in the list. I want to store similar book names with multiplication of number of occurrence of that book name in the list inside a string variable called string BooksName as a comma separated string, so when I retrieve BooksName i will have one comma separated string value like this

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

Because I have 2 of book1, 2 of book2, 1 of book3 and 3 of book4 in the list.

I tried following linq but it did not work

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

After How can I do that?

Thank you professionals in advance

You just need to order the results of GroupBy , modify how you are selecting the book name for display, and use 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; }
}

You can't just .ToString an enumerable, you need to use string.Join instead:.

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}")
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM