我想创建一个程序来读取文本文件(书名),并将每个书名对应一个用户评级。我如何为阵列中的书名分配多个评级?
到目前为止,我有,
class Program
{
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("books.txt");
}
用户评级位于此表单的单独文本文件中:
User:a
2
5
4
1
1
User:b
5
5
0
1
2
如果有5本书和2位用户,我如何将2和5的分数与一本名为“饥饿游戏玩家”的书联系起来?
答案 0 :(得分:1)
这里似乎有3个数据:书籍,用户和评级。你可以为每一个创建结构并用适当的数据填充它们,然后你可以用它们做各种有趣的事情。
以下是一个例子:
public class Book
{
public int ID;
public string Name;
}
public class User
{
public int ID;
public string Name;
}
public class Rating
{
public int UserID;
public int BookID;
public int Value;
}
从基本级别开始,您可以将这些项目的列表加载到数组中:
Book[] books = new Book[]
{
new Book { ID = 1, Name = "A B C" },
new Book { ID = 2, Name = "Word Two" },
new Book { ID = 3, Name = "Third Book" },
new Book { ID = 4, Name = "And Another" },
new Book { ID = 5, Name = "The Last Word" }
};
User[] users = new User[]
{
new User { ID = 1, Name = "A" },
new User { ID = 2, Name = "B" },
};
Rating[] ratings = new Rating[]
{
new Rating { UserID = 1, BookID = 1, Value = 2 },
new Rating { UserID = 1, BookID = 2, Value = 5 },
new Rating { UserID = 1, BookID = 3, Value = 4 },
new Rating { UserID = 1, BookID = 4, Value = 1 },
//new Rating { UserID = 1, BookID = 5, Value = 1 },
new Rating { UserID = 2, BookID = 1, Value = 5 },
new Rating { UserID = 2, BookID = 2, Value = 5 },
new Rating { UserID = 2, BookID = 3, Value = 0 },
new Rating { UserID = 2, BookID = 4, Value = 1 },
//new Rating { UserID = 2, BookID = 5, Value = 2 },
};
现在为了一些有趣的事情......
您收藏集中所有图书的平均评分列表(包括没有评分的图书,我在ratings
初始化程序中评论的图书):
var bookRatings =
// start with books
from bk in books
// get all the ratings related to each book...
join r in ratings on bk.ID equals r.BookID into _ratings
// put a default value (null, no value) when no ratings were found
from r in _ratings.DefaultIfEmpty()
// now group the ratings by book
group (r == null ? null : (int?)r.Value) by bk into grp
// and now do some calculations:
select new
{
grp.Key.ID,
grp.Key.Name,
Rating = grp.Average(),
NumRatings = grp.Count(v => v != null)
};
// Now display it:
foreach (var result in bookRatings)
Console.WriteLine("{0}\t{1,-15}\t{2}\t{3}", result.ID, result.Name, result.Rating, result.NumRatings);
这是输出:
1 A B C 3.5 2
2 Word Two 5 2
3 Third Book 2 2
4 And Another 1 2
5 The Last Word 0
我已经使用了classes,arrays,anonymous types以及一些相当有趣的LINQ表格,但这些都是很好的学习内容。点击链接并进行一些阅读,直到您了解上面发生的大部分内容为止。
顺便提一下,如果我将数据存储在数据库中,上面几乎就是我要做的事情 - 整体结构相同,几乎相同的代码。转换时,LINQ to SQL消除了很多实施的痛苦。
答案 1 :(得分:0)
您可以在此处使用Dictionary。喜欢这个
Dictionary<string, List<int>> bookMapping = new Dictionary<string, List<int>>();
bookMapping.Add("youruserkey", new List<int> { 1, 2, 3, 4, 5 });
PS:请详细阅读链接的详细信息。