Using LINQ, how I can retrieve list of list of item where match with another list?
Example:
List<string> data = new List<string>();
List<List<string>> datas = new List<List<string>>();
List<string> dataSearch = new List<string>();
dataSearch.Add("01");
dataSearch.Add("02");
data.Add("01");
data.Add("Book");
data.Add("9");
datas.Add(data);
data = new List<string>();
data.Add("02");
data.Add("Pen");
data.Add("2");
datas.Add(data);
data = new List<string>();
data.Add("03");
data.Add("Pencil");
data.Add("5");
datas.Add(data);
Expected Result in List<List<string>>:
List<string> ("01", "Book", "9")
List<string> ("02", "Pen", "2")
I try
var result = datas.Where(x => x[0].Contains(dataSearch)).ToList();
I got red underline in editor.
This is what you are looking for:
List<string> data = new List<string>();
List<List<string>> datas = new List<List<string>>();
List<string> dataSearch = new List<string>();
dataSearch.Add("01");
dataSearch.Add("02");
// same as your code
var result = datas.Where(i => dataSearch.Contains(i[0])).ToList();
If the three items in the List<List<string>> has a closely bound relationship it is better to create a class for this and then make a list of these objects.
Class StationaryItem
{
int ItemCode;
String ItemName;
float Price;
public StationaryItem(int Code, string ItemName,float Price)
{
this.ItemCode = Code;
this.ItemName = ItemName;
this.Price = Price;
}
}
public static void Main ()
{
List<StationaryItem> ItemList = new List<StationaryItems>
ItemList.Add( new StationaryItem(01,"Pen",20));
ItemList.Add( new StationaryItem(02,"Pencil",5));
//After you make a class like this you can use Linq to manuplate easily
}
Related
Is it possible to add a variable to a list name when using it?
Something like this:
string id = "1"; //Could be 2
List<string> List1 = new List<string> {"1","11" };
List<string> List2 = new List<string> {"2","22" };
foreach (var element in List+id)
{ //code here }
IDs could be a dozen different values, so I didn't even try with regular if(). Would that be the only way?
Use a dictionary:
var dict = new Dictionary<string, List<string>>();
dict.Add("1", new List<string> {"1","11" });
dict.Add("2", new List<string> {"2","22" });
Then you can do
foreach (var element in dict[id])
{
}
con001.Open();
SqlCommand cmd001 = new SqlCommand("select distinct TruckRegistration.Id from booking_txn inner join Payments on booking_txn.booking_ID=Payments.booking_ID inner join truck_log on booking_txn.booking_ID=truck_log.booking_id inner join TruckRegistration on TruckRegistration.Id=truck_log.truck_id inner join booking_master on booking_master.booking_ID=booking_txn.booking_ID where booking_master.booking_pickupdate between '10-Jul-2016' and '10-Aug-2016' ", con001);
DataTable myDataTable = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(cmd001);
con001.Close();
ad.Fill(myDataTable);
List<String> trucklist = new List<String>();
foreach (DataRow dataRow in myDataTable.Rows)
{
trucklist.Add(string.Join(";", dataRow.ItemArray.Select(item => item.ToString())));
}
*I Have stored values from a datatable to trucklist array*
After this what is to be done is, to store every value in array to seperate string using for loop.
foreach (String currentTruck in truckList)
{
// do something with currentTruck
}
or
for (int i = 0; i < truckList.Count; i++)
{
String currentTruck = truckList[i];
// do something with currentTruck
}
Your example is similar to the code below, which will just fill 2,3,4,5 at different indexes of the stringList. If beside Id one more column is added to the class A, then would have some impact of string.Join
void Main()
{
List<A> intList = new List<A> { new A { Id = 2}, new A { Id = 3}, new A { Id = 4}, new A { Id = 5}};
List<string> stringList = new List<string>();
var propertyArray = intList.First().GetType().GetProperties();
foreach (var x in intList)
{
stringList.Add(string.Join(";",propertyArray.Select(y => y.GetValue(x,null))));
}
// Print StringList
}
public class A
{
public int Id { get; set;}
}
Edit
Convert to Array, use following code:
var stringArray = stringList.ToArray();
I have a list of strings which holds file paths.
List<string> allFilesWithPathList = new List<string>();
allFilesWithPathList.Add(#"G:\Test\A.sql");
allFilesWithPathList.Add(#"G:\Test\B.sql");
allFilesWithPathList.Add(#"G:\Test\C.sql");
return allFilesWithPathList;
I have another list which holds a subset of files – but it has only the file name; not the path.
List<string> excludeList = new List<string>();
excludeList.Add("B.sql");
Now I need to get files from allFilesWithPathList that is not present in excludeList. Currently I am doing the following, using EXCEPT, after creating another list with file names only.
List<string> allFileNamesOnlyList = new List<string>();
foreach (string fileNameWithPath in allFilesWithPathList)
{
//Remove path and get only file name
int pos = fileNameWithPath.LastIndexOf(#"\") + 1;
string value = fileNameWithPath.Substring(pos, fileNameWithPath.Length - pos);
allFileNamesOnlyList.Add(value);
}
//EXCEPT logic
List<string> eligibleListToProcess = allFileNamesOnlyList.Except(excludeList).ToList();
What is the best way in LINQ to get this logic working without introducing another list like the above?
Note: I am using .Net 4.5
Complete code
class Program
{
static void Main(string[] args)
{
List<string> allFilesWithPathList = GetAllFilesWithPath();
List<string> excludeList = new List<string>();
excludeList.Add("B.sql");
List<string> allFileNamesOnlyList = new List<string>();
foreach (string fileNameWithPath in allFilesWithPathList)
{
//Remove path and get only file name
int pos = fileNameWithPath.LastIndexOf(#"\") + 1;
string value = fileNameWithPath.Substring(pos, fileNameWithPath.Length - pos);
allFileNamesOnlyList.Add(value);
}
//EXCEPT logic
List<string> eligibleListToProcess = allFileNamesOnlyList.Except(excludeList).ToList();
//Print all eligible files
foreach (string s in eligibleListToProcess)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
public static List<string> GetAllFilesWithPath()
{
List<string> allFilesWithPathList = new List<string>();
allFilesWithPathList.Add(#"G:\Test\A.sql");
allFilesWithPathList.Add(#"G:\Test\B.sql");
allFilesWithPathList.Add(#"G:\Test\C.sql");
return allFilesWithPathList;
}
}
allFilesWithPathList.Where(path => !allFileNamesOnlyList.Contains(Path.GetFileName(path));
There are two improvements here.
Path.GetFileName is much better than splitting the path yourself.
IEnumerable.Where in conjunction with ICollection.Contains to actually query the list in a succinct and easy to read way.
This should work
allFilesWithPathList.Where(x => !excludeList.Any(y => x.EndsWith(y)))
I want a method to return a list which contains two more list which are having two different data types, like :
List<List<object>> parentList = new List<List<object>>();
List<string> childList1 = new List<string>();
List<DataRow> childList2 = new List<DataRow>();
parentList.Add(childList1);
parentList.Add(childList2);
return parentList;
As per above code I am getting an error
The best overloaded method match for 'System.Collections.Generic.List>.Add(System.Collections.Generic.List)' has some invalid arguments
Please can anyone suggest me the best approach to handle this.
Thanks
What about creating an object of your class as like this?
public class myParent
{
public List<string> childList1 = new List<string>();
public List<DataRow> childList2 = new List<DataRow>();
}
public void someFun()
{
List<myParent> parentList = new List<myParent>();
myParent myParentObject = new myParent();
myParentObject.childList1 = new List<string>() { "sample" };
myParentObject.childList2 = new List<DataRow>() { };
parentList.Add(myParentObject);
}
I'm not sure why would you like to mix objects like this, but you could use ArrayList for this. Refer example below:
List<ArrayList> data = new List<ArrayList>();
data.Add(new ArrayList(){12, "12"}); //Added number and string in ArrayList
data.Add(new ArrayList() {"12", new object() }); //Added string and object in ArrayList
Update
In your case the using the array list like below could be better
var data = new ArrayList();
data.Add(new List<object>());
data.Add(new List<string>());
data.Add(new List<int>());
example...
List<array> thisListOfArray = new List<array>();
List<string> thisArrayA= new List<string>();
List<string> gMaintenanceB = new List<string>();
thisArrayA.Add("ItemA1");
thisArrayA.Add("ItemA2");
thisArrayA.Add("ItemA3");
thisArrayB.Add("ItemB1");
thisArrayB.Add("ItemB2");
thisArrayB.Add("ItemB3");
thisListOfArray.Add(thisArrayA.ToArray());
thisListOfArray.Add(thisArrayB.ToArray());
I want to get every value that I have inputted inside the thisListOfArray.
you can get it following way. here is the code
List<string[]> thisListOfArray = new List<string[]>();
List<string> thisArrayA = new List<string>();
List<string> thisArrayB = new List<string>();
thisArrayA.Add("ItemA1");
thisArrayA.Add("ItemA2");
thisArrayA.Add("ItemA3");
thisArrayB.Add("ItemB1");
thisArrayB.Add("ItemB2");
thisArrayB.Add("ItemB3");
thisListOfArray.Add(thisArrayA.ToArray());
thisListOfArray.Add(thisArrayB.ToArray());
List<string> lstNewstring = new List<string>();
foreach (var strArray in thisListOfArray)
{
foreach (var str in strArray)
{
lstNewstring.Add(str);
}
}
MessageBox.Show(lstNewstring.Count.ToString());
Change your code like this:
List<List<string>> thisListOfArray = new List<List<string>>();
List<string> thisArrayA = new List<string>();
List<string> gMaintenanceB = new List<string>();
thisArrayA.Add("ItemA1");
thisArrayA.Add("ItemA2");
thisArrayA.Add("ItemA3");
gMaintenanceB.Add("ItemB1");
gMaintenanceB.Add("ItemB2");
gMaintenanceB.Add("ItemB3");
thisListOfArray.Add(thisArrayA);
thisListOfArray.Add(gMaintenanceB);
foreach (var itm in thisListOfArray.SelectMany(item => item))
{
MessageBox.Show(itm);
}
If you have:
List<string[]> listOfArray
string[] array
Add the array to the List with listOfArray.Add(array);
Not sure where you'll be getting array from.