星期四, 7月 10, 2008

(簡單範例)判斷開會時間是否有重複

在論壇上有看到這問題..寫個間單範例..Tongue..

//把開會時間資料抓出來(資料是假設的)
meetingTime[] source = new meetingTime[]
{
new meetingTime() {meeting="m1", startTime= new DateTime(2008, 7, 10, 8, 0, 0),
endTime= new DateTime(2008, 7, 10, 10, 0, 0) },
new meetingTime() {meeting="m2", startTime= new DateTime(2008, 7, 10, 7, 30, 0),
endTime= new DateTime(2008, 7, 10, 9, 0, 0) },
new meetingTime() {meeting="m3",startTime= new DateTime(2008, 7, 10, 13, 30, 0),
endTime= new DateTime(2008, 7, 10, 14, 0, 0) },
new meetingTime() {meeting="m4",startTime= new DateTime(2008, 7, 10, 16, 20, 0),
endTime= new DateTime(2008, 7, 10, 17, 0, 0) },
new meetingTime() {meeting="m5",startTime= new DateTime(2008, 7, 10, 16, 30, 0),
endTime= new DateTime(2008, 7, 10, 19, 0, 0) }
};

//資料傳入class
string strT = checkMeeting.check(source);

//列出資料
Response.Write(strT);

public class checkMeeting
{
public static string check(meetingTime[] meetingTimeArr)
{
string strT = string.Empty;
List<string> liMettingName = new List<string>();

//自己跑自己迴圈判斷是否有重複
foreach (var a in meetingTimeArr)
{
var bbbb =
meetingTimeArr.Where(b => (b.startTime <= a.startTime && a.startTime <= b.endTime) ||
(b.startTime <= a.endTime && a.endTime <= b.endTime));

foreach (var b in bbbb)
{
//判斷是否為同一筆,相同的資料不重複列印
if (b.meeting != a.meeting && !liMettingName.Contains(b.meeting))
{
strT += string.Format("{0} 和 {1} 時間重複..<br />", a.meeting, b.meeting);
liMettingName.Add(a.meeting);
}
}
}

return strT;
}
}

public class meetingTime
{
public string meeting;
public DateTime startTime;
public DateTime endTime;
}

範例結果:
m1 和 m2 時間重複..
m4 和 m5 時間重複..

參考一下ㄅ..


---------------------------------------------------------------------------------------------
邏輯好的解法..Thumbs-up..(Johnny.Net大大提供)

SELECT * FROM [YourTableName] WHERE ([EndTime] > @StartTime) AND ([StartTime] < @EndTime) 

---------------------------------------------------------------------------------------------
翔大..提供Overlap情況的圖..Thumbs-up
overlapwo6

4 則留言:

Allen Kuo 提到...

利用開始/結束時間,計算出一個key值,判斷時,只要準備一個有key/value的物件,並用一個迴圈,將一個個key值判斷是否已存在,若不存在,就加入,可能會比較簡單一些

Allen Kuo 提到...

sorry我好像會錯意了,如果要找出時間完全相同的,可以用key來找,如果要找時間重覆的,就要比較二者的開始/結束時間了, 但驗證是否重覆的邏輯,不妨寫在meetingTime class裡,不要寫在check()裡

Bibby 提到...

收到..^^..

提到...

Overlap 情況蠻多的,參考:
http://img90.imageshack.us/img90/9278/overlapwo6.jpg