나는 Linq와 함께 큰 놈이고 배우려고 노력하고 있지만 여기서는 차단 지점에 도달했습니다. 나는 형의 구조가 :Linq 쿼리
Dictionary<MyType, List<MyObj>>
을 그리고 난 Linq에와 사전 내에서 하나 개 이상의 목록에 나타나는 모든하여 MyObj 인스턴스를 추출하는 구조를 조회하고 싶습니다.
이러한 쿼리는 어떻게 생겼을까요?
감사합니다.
나는 Linq와 함께 큰 놈이고 배우려고 노력하고 있지만 여기서는 차단 지점에 도달했습니다. 나는 형의 구조가 :Linq 쿼리
Dictionary<MyType, List<MyObj>>
을 그리고 난 Linq에와 사전 내에서 하나 개 이상의 목록에 나타나는 모든하여 MyObj 인스턴스를 추출하는 구조를 조회하고 싶습니다.
이러한 쿼리는 어떻게 생겼을까요?
감사합니다.
from myObjectList in myObjectDictionary.Values
from myObject in myObjectList.Distinct()
group myObject by myObject into myObjectGroup
where myObjectGroup.Skip(1).Any()
select myObjectGroup.Key
Distinct()
각 목록은 동일한 전적으로 반복 MyObj
인스턴스를 보장 목록은보고되지 않습니다.
당신은 같은 것을 할 수있는 :
var multipleObjs =
MyObjDictionary.Values // Aggrigate all the List<MyObj> values into a single list
.SelectMany(list => list) // Aggrigate all the MyObjs from each List<MyObj> into a single IEnumerable
.GroupBy(obj => obj) // Group by the Obj itself (Or an ID or unique property on them if it exists)
.Where(group => group.Count() >= 2) // Filter out any group with less then 2 objects
.Select(group => group.Key); // Re-Select the objects using the key.
편집
을 나는하여 MyObj이 같은 목록에 여러 번 발생할 경우 문제가되지 않도록,이 또한 diffrently 읽을 수 있음을 실현 , 그러나 여러 번 발생하는 경우에만 번 목록에 있습니다. 우리는 초기에는 더 MyObjs의 목록을 aggrigating 때이 경우, 우리는 고유 값을 선택하거나 약간 diffrent 쿼리를 사용할 수 있습니다
var multipleObjs =
MyObjDictionary.Values // Aggrigate all the List<MyObj> values into a single list
.SelectMany(v => v.Distinct()) // Aggrigate all distinct MyObjs from each List<MyObj> into a single IEnumerable
.GroupBy(obj => obj) // Group by the Obj itself (Or an ID or unique property on them if it exists)
.Where(group => group.Count() >= 2) // Filter out any group with less then 2 objects
.Select(group => group.Key); // Re-Select the objects using the key.
var multipleObjs =
MyObjDictionary.SelectMany(kvp => // Select from all the KeyValuePairs
kvp.Value.Where(obj =>
MyObjDictionary.Any(kvp2 => // Where any of the KeyValuePairs
(kvp.Key != kvp2.Key) // Is Not the current KeyValuePair
&& kvp.Value.Contains(obj)))); // And also contains the same MyObj.
SelectMany (v => v)로해야합니까? (v.Select (obj => obj) 필요 없음) –
네 말이 맞아. 필자는 일반적으로 더 복잡한 쿼리에서 무엇을 선택하는지 명시 적으로 작성합니다. 이후에 진행되는 작업을 추적하고 나중에 최적화하는 것이 더 쉽기 때문에이 경우 잊어 버렸습니다. 어쨌든 지금은 고쳐졌습니다. – rmoore
Count()는 각 그룹을 전체적으로 나열합니다. Skip (1) .Any()를 사용하는 것이 더 효율적입니다. –