我想制作一个程序,读取一个文本文件(书名),并使每个书名与用户评分相对应。如何为数组中的书名分配多个评级?
到目前为止,
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分和5分和一本叫做“饥饿游戏者”的书联系起来呢?
发布于 2014-03-26 05:08:29
您可以在这里使用字典。像这样
Dictionary<string, List<int>> bookMapping = new Dictionary<string, List<int>>();
bookMapping.Add("youruserkey", new List<int> { 1, 2, 3, 4, 5 });PS:一定要详细阅读链接的工作原理。
发布于 2014-03-26 22:49:02
似乎你在这里有三个数据:书,用户和评级。您可以为其中的每一个创建结构,并用适当的数据填充它们,然后您可以使用它们做各种有趣的事情。
下面是一个例子:
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我使用过类、列阵、匿名类型和一些非常有趣的林克表单,但这些都是值得学习的好东西。单击链接并进行一些阅读,直到您了解上面所发生的大部分事情。
顺便说一句,如果我将数据存储在数据库中,那么上面的内容几乎就是我所要做的--总体上是相同的结构,而且代码也差不多。当您进行转换时,LINQ到SQL消除了许多实现的痛苦。
https://stackoverflow.com/questions/22651747
复制相似问题