我有兩個長度相同的串列。如果一個串列有 4 個元素,則另一個串列也有 4 個元素。
List<string> multipleJMBGs和List<BundleSchedule> schedules
我需要創建一個檢查方法,它將檢查以下內容:
首先檢查是否有任何重復項
List<string>,如果有,然后從該查詢中獲取索引,并在這些索引中檢查計劃是否具有相同的 Idif schedules[x].Id == chedules[y].Id可以有多個相同的對,例如:
"1111", "1111" (indexes [23],[41])
"12345", "12345" (indexes [3],[11])
"16872982342716", "16872982342716" (indexes [29],[33])
那些是 3 對,所以我們需要 groupBy,并提取它們的索引(這些數字僅用于示例目的):
private bool CheckIfSameUsersHaveSameServices(List<string> multipleJMBGs, List<BundleSchedule> schedules)
{
var duplicateJMBGs = multipleJMBGs.GroupBy(x => x)
.Where(group => group.Count() > 1)
.Select(group => new { jmbg = group.Key }).ToList();
Dictionary<string, string> indexes = new Dictionary<string, string>();
//fill in dictionary with indexes
//23,41
//3,11
//29,33
foreach (var pair in indexes)
{
var firstToCompare = schedules.ElementAt(Convert.ToInt32(pair.Key));
var secondToCompare = schedules.ElementAt(Convert.ToInt32(pair.Value));
//if only one compared pair has same serviceId, return true
if (firstToCompare.ServiceTypeComplexityId == secondToCompare.ServiceTypeComplexityId)
{
return true;
}
}
}
我的問題是如何放入 Select of GroupBy 查詢串列中的那些索引?
uj5u.com熱心網友回復:
怎么樣:
Dictionary<string, int> jmbgIds = new Dictionary<string, int>(StringComparer.Ordinal);
for (int index = 0; index < multipleJMBGs.Count; index )
{
string jmbg = multipleJMBGs[index];
int id = schedules[index].ServiceTypeComplexityId;
if (jmbgIds.TryGetValue(jmbg, out var previousId))
{
if (previousId != id)
{
return false;
}
}
else
{
jmbgIds.Add(jmbg, id);
}
}
return true;
uj5u.com熱心網友回復:
您可以獲得每個可列舉的索引和值并執行連接。小提琴:https : //dotnetfiddle.net/0oDJMM
public static void Main()
{
List<string> foo = new List<string>() {
"1", "12", "123", "1234", "12345"
};
List<string> bar = new List<string>() {
"123", "a", "b", "1", "12"
};
var foos = foo.Select((f, i) => new { idx = i, val = f });
var bars = bar.Select((b, i) => new { idx = i, val = b });
var indexes = foos.Join(bars,
f => f.val,
b => b.val,
(f, b) => new { idxA = f.idx, idxB = b.idx });
foreach (var idxs in indexes) {
Console.WriteLine("idxA: {0} idxB: {1}", idxs.idxA, idxs.idxB); // You can now access the indexes for the matching values
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/365686.html
標籤:C# 。网 asp.net-mvc 林克
上一篇:具有泛型型別檢查的泛型方法呼叫
