问题描述
我正在尝试从数据库中选择数据,但我收到重复的数据。
情景是:
我有2条记录在这个数据库中:
RoomId RoomTitle RoomName Room价格
1房间1房间1 200
2房间2房间2 250
这是我在C#中的代码:
I am trying to select data from database but I am getting duplicate data.
The Scenario is :
I have 2 records in the database like this:
RoomId RoomTitle RoomName RoomPrice
1 Room1 Room1 200
2 Room2 Room2 250
And this is my code in C#:
public static List<RoomInfo> GetAvailRoom(string Checkin, string Checkout)
{
DateTime CheckinDate = DateTime.ParseExact(Checkin, "M/dd/yyyy", CultureInfo.InvariantCulture.DateTimeFormat);
DateTime CheckoutDate = DateTime.ParseExact(Checkout, "M/dd/yyyy", CultureInfo.InvariantCulture.DateTimeFormat);
List<RoomInfo> lstRooms = RoomInfo.GetRooms();
List<RoomImage> lstRoomImages = new List<RoomImage>();
List<RoomInfo> lstRoomsNew = new List<RoomInfo>();
RoomInfo _RoomInfo = new RoomInfo();
foreach (var roomitems in lstRooms)
{
_RoomInfo.Checkin = CheckinDate;
_RoomInfo.Checkout = CheckoutDate;
var roomAvailable = _RoomInfo.GetAvailableRoomByDate();
foreach (var items in roomAvailable)
{
_RoomInfo.RoomId = items.RoomId;
_RoomInfo.RoomTitle = items.RoomTitle;
_RoomInfo.RoomName = items.RoomName;
_RoomInfo.RoomPrice = items.RoomPrice;
_RoomInfo.RoomDescription = items.RoomDescription;
_RoomInfo.IsBookButton = items.IsBookButton;
if (_RoomInfo.RoomId > 0)
{
RoomImage _RoomImage = new RoomImage();
_RoomImage.RoomId = _RoomInfo.RoomId;
var LstOfImages = _RoomImage.GetRoomImagesByRoomId();
HttpContext.Current.Session["RoomId"] = _RoomInfo.RoomId;
foreach (var images in LstOfImages)
{
_RoomInfo.RoomImageId = images.RoomImageId;
_RoomInfo.RoomId = images.RoomId;
_RoomInfo.LSTImages = LstOfImages;
}
}
else
{
string lblMsgError = string.Empty;
lblMsgError += string.Format("<div id=\"ShowError\" class=\"NotificationError\">{0}</div>", _RoomInfo.RoomNotAvailable);
}
}
lstRoomsNew.Add(_RoomInfo); // Here is the problem I think.
}
return lstRoomsNew;
}
没问题,我只获得第二条记录一式两份,意味着2次:
2房间2房间250 250
现在的问题是,只需检查这一行:lstRoomsNew.Add(_RoomInfo); //这就是我想的问题。
我认为这是有问题的地方。在那一行。
请有人帮忙。
No the problem is, I am getting the second record only in duplicate, means 2 times:
2 Room2 Room2 250
Now the thing is, just check on this line: lstRoomsNew.Add(_RoomInfo); // Here is the problem I think.
I think it is where there is a problem. On that line.
Please can someone help.
推荐答案
RoomInfo _RoomInfo = new RoomInfo();
foreach (var roomitems in lstRooms)
{
_RoomInfo.Checkin = CheckinDate;
...
lstRoomsNew.Add(_RoomInfo); // Here is the problem I think.
}
因此,当你查看你的收藏时,你会看到两次相同的数据。
在循环中移动实例创建:
So when you look at your collection, you see the same data twice.
Move the instance creation inside the loop:
foreach (var roomitems in lstRooms)
{
RoomInfo _RoomInfo = new RoomInfo();
_RoomInfo.Checkin = CheckinDate;
...
lstRoomsNew.Add(_RoomInfo); // Here is the problem I think.
}
它会做你想要的 - 因为现在你为每组数据创建了新的房间。
And it'll do what you want - because now you create new rooms for each set of data.
这篇关于将项添加到通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!