Linq - get unavailable IDs in a list using linq - c#

I have a ID list as "100,1025,5341" and a objects list. I want to get the IDs which are not include in my object list.
as an example, lets assume that objects list contains both 100 and 5341 as a property (eg: ID). I want to get 1025 as my result. I know that this request make no sense but i want to get that somehow. I can easily use,
string idList = "100,1025,5341";
var objectList = _dataService.GetData();
var result = objectList.Any(item=> idList.Contains(item.ID));
to get the list items which are having given IDs. But i want get other way. I want get the IDs which are not exists in the list.

Use Except:
var ids= idList.Split(',').Select(int.Parse);
var result = objectList.Where(item=> ids.Contains(item.ID));
var r= objectList.Except(result);
If you want only the ids that are not include in your object list, then you can do the following
var ids= idList.Split(',').Select(int.Parse);
var r= ids.Except(ids.Where(i=> objectList.Any(item=> item.ID==i)));

It will get you Ids from idList which are not Ids of objectList. If I undestood correctly what you want...
var ids = objectList.Select(x=>x.ID).ToList();
var otherIdsList = idList.Split(',').Select(x=>int.Parse(x)).ToList().Where(x=> !ids.Contains(x)).ToList();

Related

Getting the selected datalist by an array

I am going to ask a very basic question and probably a repeated one but I have a bit different situation.
I want to use "in" operator in Linq.
I have to get all the rows from table which has Id provided
by my array and returns the row if it has. How can I do it.
My array has
var aa="1091","1092","1093" and so on.
and my table uses these Ids as Primary keys
.I have to get all the rows whose Id is contained in the array and I do not want to use S.P.
You can use Enumerable.Contains,
var aa = new string[3] { "1091", "1092", "1093" };
var res = yourDataSource.Where(c => aa.Contains(c.ID));
IN statements are created by using Contains in your Where call. Assuming you use integers as IDs, you could write something like this:
var myArray=new[]{1091,1092,1094};
var myEntities=from entity in myTable
where myArray.Contains(entity.ID)
select entity;

Sorting list of items according to another fixed list

I'm very beginner in C#.
I have a List of
private List<String> mXMLProdcutsIDs = new List<String>();
mXMLProductsIDs is like
{"megapack", "levelpack","bikepack"}.
Sometimes I get another list which is in random order, {"megapack", "levelpack","bikepack"}
I would like to resort that list according to the mXMLProductIDs list order
You can use index of string in original list to define items order:
var result = anotherList.OrderBy(s => mXMLProdcutsIDs.IndexOf(s));
Shorten version:
var result = anotherList.OrderBy(mXMLProdcutsIDs.IndexOf);
Keep in mind, that result will be IEnumerable<string>. You can use ToList() if you need to save results in list.
Another option (if you don't have duplicated items in another list):
var result = mXMLProdcutsIDs.Intersect(anotherList);

Linq query to filter id inside a list of list c#

I have a list of result List where it contains List inside of it.I have another list where it contains List alone.I want to filter using a linq query from the data where it should return all the data which contains skill id from the second list.
var list = this._viewModel.Data.Select(T => T.SkillsList);
var filtered = item.Skills.Contains(list.Where(t=>t.ToString()).ToList();
from the first list it contains List of decimals inside the skill list;
item.Skills contains list where the fields are skillid and code.
item is another object which contains the skillslist.
if skillId is a variable and assuming that SkillsList contains a property called Id. Then the following would work in getting you any data that has the specified skillId.
var list = this._viewModel.Data.Where(t=>t.SkillsList.Any(s=>s.Id == skillId));
If Skillslist is just an array of integers then the following would work.
var list = this._viewModel.Data.Where(t=>t.SkillsList.Any(s=> s == skillId));
Now if you are checking against a list the following would work.
var list = this._viewModel.Data.Where(t=>t.SkillsList.Any(s=> skillsList.contains(s));

Compare to list<String> using linq?

I have 3 list List
ListMaster contains {1,2,3,4,....} ..getting populated from DB
List1 contains {1,3,4}
List2 contains {1,3,95}
how to check Which list items are present in master list using linq
var inMaster = List1.Intersect(ListMaster);
or for both list :
var inMaster = List1.Intersect(List2).Intersect(ListMaster);
check if any item from list1, list2 exist in master
var existInMaster = inMaster.Any();
You can use Enumerable.Intersect:
var inMaster = ListMaster.Intersect(List1.Concat(List2));
If you want to know which are in List1 which are not in the master-list, use Except:
var newInList1 = List1.Except(ListMaster);
and for List2:
var newInList2 = List2.Except(ListMaster);
Can i use a list .all to check all item of a list in another list for
list of string
So you want to know if all items of one list are in another list. Then using Except + Any is much more efficient(if the lists are large) because Intersect and Except are using sets internally whereas All loops all elements.
So for example, does the master-list contain all strings of List1 and List2?
bool allInMaster = !List1.Concat(List2).Except(ListMaster).Any();
You can use Enumerable.Intersect method like;
Produces the set intersection of two sequences by using the default
equality comparer to compare values.
var inMaster1 = List1.Intersect(ListMaster);
var inMaster2 = List2.Intersect(ListMaster);
Here is a DEMO.

How do I get a usabled List object for this code in C# using LINQ to XML?

Newbie to C# here....
I have the following code:
var xdoc = XDocument.Parse(xml);
var result = xdoc.Root.Elements("item")
.Select(itemElem => itemElem.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value))
.ToList();
but when I try to use result as I would any List object, such as result.Item, it doesn't work.
What am I doing wrong? Why is result not coming back as a normal List object that I can manipluate in my code? Do I need to make another List object from it?
I am just trying to get the first Dictionary item out of the List and use it.
It depends on what you expected. Your code currently produces a List<Dictionary<string,string>>. So each entry in the list would be a dictionary.
You can access each dictionary as you usually would access list elements, i.e.
string firstResult = result[0]["key"];
The first part [0] is the indexer of the list the second part ["key"] is the indexer of the dictionary - this would return the value for the key "key" of the first dictionary in your list.
This assumes the list has at least one entry though for which you would have to check.
This is a List<Dictionary<String, String>>. Each element in the list is a Dictionary.
It would help to know what you wanted to do with it.
But some examples are:
//Get the First Dictionary Item, then Iterate through all the items in the first dictionary.
var firstItem = results.First();
foreach(var kvPair in firstItem)
{
var key = kvPair.Key;
var val = kvPair.Value;
}
//Loop through each Dictionary getting values from each.
foreach (var result in results)
{
var wordValue = result["word"];
var defValue = result["def"];
}
//Create a list of all the values for the Elements with the key "word".
var valuesForAllWords =
results
.Select(r => r["word"])

Categories